COROUTINES


Coroutines are a way to pause and resume the execution of code in Lua and PICO-8. 

A function is a reusable piece of code that performs a specific task, but if you exit a function, and want to continue it, then the entire function must run again. Coroutines are similar to functions, but they can be paused and resumed at any point in their execution. This means that you can write code that yields (pauses) and resumes (unpauses) at specific points, allowing you to control the flow of execution in a more fine-grained way.


To create a coroutine, use cocreate(function):

c = cocreate(f)

The function passed into cocreate() can then call yield() to pause running the function and return control to the main program. Usually, you'll see yield() in a loop.


To pause a coroutine, use yield(), and to resume it from that yielded point, use coresume():

function dialog()
	print("hello")
	yield()               --pause
	print("world")
	yield()               --pause
	print("how are you?")
end

c = cocreate(dialog)

function _update()
	if btnp(4) then 
		coresume(co) 
	end
end

Having functions that can pause and resume where they left off can be incredibly useful in game development, especially for creating game logic that involves complex or time-consuming tasks. Here are a few examples of how coroutines can be used in game development:

1. Animations:
To create complex animations that involve multiple steps or actions. By breaking the animation down into smaller steps and using coroutines to sequence them, developers can create animations that are more realistic and visually impressive.

2. AI behavior: To create more advanced AI behavior for non-player characters (NPCs) in games. For example, a coroutine could be used to make an NPC "look around" periodically, or to make them move to a new location over time.

3. Cutscenes: To create more dynamic and interactive cutscenes in games. By using coroutines to control the camera, animations, and other elements of the scene, developers can create cutscenes that feel more like a part of the game world.

4. Tutorials: To create more engaging and interactive tutorials to teach the rules of your game. Coroutines can automate actions in your game, then pause to explain what is happening, and resume the gameplay after a player acknowledges by pressing the correct button.


To check the current status of a coroutine, use costatus(c) :

status = costatus(c)

This function will return 3 possible strings:

"running" or "suspended" or "dead"


822

6 Apr 2023

Font