Log In  


Cart #hipajokimu-0 | 2025-07-28 | Code ▽ | Embed ▽ | No License

Coroutine bug

Looks like multiple coroutines of same function have shared memory on coresume+yield pairs (or local variable space)
That leads to no uniqueness of coroutines and unexpected behaviour

Steps to reproduce:

  • Create 2+ entities
  • For each entity add unique coroutine of same function
  • Function should have entity as an argument
  • Function should have local variable at the beginning
  • Coresume each entitys coroutine passing entity as an arguement
  • Get yield() result inside function (argument of coresume)
  • Operate on yielded entity

After operating on yielded entity it seems that our separated entities were somehow operated by same coroutine.
Or maybe local variables of coroutined function were shared across multiple coroutines

Example

There are two bugs with random colors at start
First 2 seconds we see them, but then color is swapped to red
After 2 more seconds their color should be returned to initial, but as we see they are same color now

Code

function entity(x,y)
	return {
		x=x,y=y,
		clr=1+rnd(15)\1,
		animate=cocreate(animate),
		crid=0
	}
end

function _init()
	e1=entity(48,64)
	e2=entity(64,64)
end

function _update60()
	coresume(e1.animate,e1)
	coresume(e2.animate,e2)
end

function _draw()
	cls(0)
	pal(6,e1.clr,0)
	print(e1.crid,e1.x,e1.y-16)
	spr(1,e1.x,e1.y)
	pal(6,e2.clr,0)
	print(e2.crid,e2.x,e2.y-16)
	spr(1,e2.x,e2.y)
	pal(0)
end

function animate(e)
	local id=rnd(99)\1 clr=e.clr
	e.crid=id
	for i=1,120 do
		e=yield()
	end
	e.clr=8
	e.crid=id
	for i=1,120 do
		e=yield()
	end
	e.clr=clr
	e.crid=id
	e.animate=cocreate(animate)
end


1

The problem is in the first line of your animate() function.

Change this,

local id=rnd(99)\1 clr=e.clr

to this

local id=rnd(99)\1
local clr=e.clr

or this

local id,clr=rnd(99)\1, e.clr

and it'll work. The way you have it, even though they're on the same line, only id is being defined as local and clr is being defined as global which is why they both end up as the same colour when they switch back.


Thank you!



[Please log in to post a comment]