Coroutines dont 'resume' at 'yield' (Lua)

Started by
9 comments, last by Endurion 15 years, 4 months ago
I'm new to coroutines and am having some issues. I have a Lua function which runs each time you click the mouse. This function resumes a coroutine, but the coroutine starts from the beginning every time instead of where it yielded. I'm not sure if I'm missing something fundamental.
function onClick()
	coroutine.resume(co)
end

co = coroutine.create( function ()

	Say( "1" )
	coroutine.yield()
	Say( "2" )
	coroutine.yield()
	Say( "3" )

end)
Every mouse click results in an output of '1'. The happens over a number of script executions, perhaps my coroutine re-initialises each execution? Thanks M
Advertisement
you say "it happens over a number of script executions".

Are you running the script again and again via dofile or dostring?
Thanks for the reply mystb.

Everytime the mouse is clicked, the script is executed using
luaL_dofile(L, scriptname);
The lua-state is never closed until the program exits, so I thought the coroutine would persist through multiple executions.
And that's your problem; each time you run the script it sets everything up again from the start to the end.

What you need to do is load the script and execute it ONCE at start up to set it up and then, on each click event, call the OnClick function, not execute the script again.
Thanks phantom, I felt that could be the issue.

To increase the complexity a bit, the script that is run depends on the NPC clicked. Am I correct that I can only have one script executing in a Lua-state at a time?

How would I handle the script changes, but also avoid the re-initialisation?

Perhaps I am handling the entire 'individual npc script' issue the wrong way.
Ah I solved it.

Im sorry, I thought coroutines had to be defined in global space, but no. It was then a simple matter of rearranging my code and calling an Init Function.

Thanks for the help, it was greatly appreciated.
M
simple:

instead of having scriptA with function onClick(), scriptB with function onClick()......, you can have each script run once and with different function definitions inside: onClickA(), onClickB(), etc.

In the end, instead of calling dofile with diferent scripts, just call diferent functions.

Hope it Helps,

DC
The other method involves using tables to store per entity information, that way you can load a script once and then use these tables to store functions and per entity data which you can then call/use from the C/C++ side.
Thankyou again phantom and mystb for all your help.

Edit: I answered my own question, so I've removed it.

[Edited by - mwmey1 on December 6, 2008 7:19:37 PM]
Hi,

What happens if we never resume a coroutine ? How will it get freed runtime ? Is there a way to say, "I am not going to resume you anymore...just go and die", to the coroutine ??

-madan

This topic is closed to new replies.

Advertisement