Log In  

Credit to MBoffin who inspired me to write this, mostly so I myself could prove that I understood seldom used Pico-8 command set of COROUTINES such as COCREATE(), CORESUME(), and YIELD().

Cart #cocreate_demo-0 | 2019-09-19 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
1

If you just want the source without the sound effects, that can be found HERE:

-- dw817's very simple
-- cocreate() program

function main() ------------->>

cls()

init=0

repeat

-- if press (x) or this is the
-- first time to run,
-- prepare for being able to
-- call function "act" as a
-- co-creation
if btnp(5) or init==0 then
  init=1

-- make a pointer for the
-- cocreation function "act"
  go=cocreate(act)
  sfx(0) -- low pitch
end

-- if press (o) then call
-- routine here to plot three
-- circles, one at a time, and
-- one for each press
if btnp(4) then
  coresume(go)
end

-- update screen
flip()

until forever
end --<<-----------------------

-- three circles, click (o)
-- three times to see all three
function act()
  circfill(10,10,10,5)
  sfx(1) -- high pitch

-- each time yield is used,
-- the position of where the
-- program is in the function
-- is recorded and the function
-- exits
  yield()

-- the second time you press
-- (o) the function will start
-- here, not at the beginning
  circfill(20,10,10,6)
  sfx(1) -- high pitch
  yield()

-- as above, this function
-- starts here on a 3rd press
  circfill(30,10,10,7)
  sfx(1) -- high pitch
  yield()

-- there is nothing more here
-- so pressing (o) a 4th or
-- more does nothing.
-- you must call cocreate()
-- again in order to reset
-- this function to start
-- running the 3-circles again
end

main()

HOPE THIS HELPS !

P#67882 2019-09-19 01:51 ( Edited 2019-09-19 02:12)

1

You are missing the key aspect: local variable state is preserved on yield.
(the whole function state is preserved actually)
Allows things like:

local j=5
for i=1,30 do
 j+=2*i
 print(j)
 yield()
end
P#67889 2019-09-19 06:22 ( Edited 2019-09-19 07:11)
:: dw817

You would think it would. It wouldn't be very useful if it didn't. :) And yes, I should write code to reflect that. Wasn't thinking at the time.

Still would be a lot easier if you could use YIELD() in any function without having to create an additional variable, and can use something like RESET(Function) to reset the pointer position in it.

P#67897 2019-09-19 17:33 ( Edited 2019-09-19 17:39)

This is a very helpful and simple example, thanks!

P#67898 2019-09-19 17:40
:: dw817

You're very welcome, hwd2002. This code is new to me too. :)

Let me see if I can find an application where the variables in it could be recalled for further use. Now if it could do a true loop and never lose its local variables, that might be useful.

P#67913 2019-09-20 00:48 ( Edited 2019-09-20 00:49)

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2020-07-15 08:13 | 0.018s | 4194k | Q:34