pico8-0hh1/coroutines.lua

34 lines
669 B
Lua
Raw Normal View History

2022-06-02 17:55:52 +02:00
local coroutines={}
2022-07-02 20:45:11 +02:00
-- starts a coroutine and saves it for future reference
function startcoroutine(fn)
assert(tostr(fn) == "[thread]") -- make sure that fn is a coroutine, the return value of cocreate()
2022-06-02 22:39:23 +02:00
add(coroutines, fn)
2022-06-02 17:55:52 +02:00
end
2022-07-02 20:45:11 +02:00
-- stops the the coroutine
2022-06-02 22:39:23 +02:00
function stopcoroutine(fn)
del(coroutines, fn)
2022-06-02 17:55:52 +02:00
end
function _coresolve()
2022-06-02 22:39:23 +02:00
for co in all(coroutines) do
2022-06-02 17:55:52 +02:00
if costatus(co)!='dead' then
2022-06-02 22:39:23 +02:00
assert(coresume(co))
2022-06-02 17:55:52 +02:00
else
2022-06-02 22:39:23 +02:00
stopcoroutine(co)
2022-06-02 17:55:52 +02:00
end
end
end
2022-07-02 20:45:11 +02:00
-- to be used inside a coroutine
2022-06-02 17:55:52 +02:00
function wait(seconds)
2022-07-12 21:47:10 +02:00
wait_frames(seconds*30)
2022-06-02 17:55:52 +02:00
end
2022-07-02 20:45:11 +02:00
-- to be used inside a coroutine
2022-06-02 17:55:52 +02:00
function wait_frames(frames)
for i=1,frames do
2022-07-12 21:47:10 +02:00
yield()
2022-06-02 17:55:52 +02:00
end
end