Skip to main content
GameDev.net gamedev.net
🔒 Locked

LUA: about coroutine and yield

Started by Rookie_Max Dec 23, 2004 at 6:42 PM 3 replies 3.8k views
Original Post
Rookie_Max
Rookie_Max
Hi, I am a newbie of Lua and got some problem abourt coroutine of Lua Following is my code: #include // Include the Lua header and make sure the linker knows it's pure C extern "C" { #include "lua\lua.h" #include "lua\luaxlib.h" } int PrintString ( lua_State * pLuaState ) { printf("I have been run\n"); return 0; } main () { lua_State *LuaMain, *LuaThread; // Initialize a Lua state LuaMain = lua_open(); //Load Script lua_dofile(LuaMain, "test.lua"); lua_register ( LuaMain, "PrintString", PrintString); LuaThread = lua_newthread(LuaMain); lua_getglobal(LuaThread, "co_func"); lua_resume(LuaThread, 0); lua_resume(LuaThread, 0); <===== seem not work Sleep(100); return 0; } Test.lua function co_func() while 1 do PrintString() coroutine.yield() end end After I run this, I expected it will show 2 line of "I have been run" in console, but I only got one. This means the secound "lua_resume" did not work Do I have something wrong in the coding? Thanks, from Rookie
Kylotan
Kylotan
You don't appear to have used coroutine.create(). Unlike Python, the function doesn't automatically become a coroutine just because you use 'yield' inside it. On the other hand, Lua coroutines are arguably more powerful than Python ones.

This link might help: http://lua-users.org/wiki/CoroutinesTutorial
Rookie_Max
Rookie_Max
I have try to modify the lua part as follow:

function co_func()
while 1 do
PrintString()
coroutine.yield()
end
end

function co_main()
PrintString()
co = coroutine.create(co_func) <~~~seem have problem while running this line
PrintString() <===seem didn't work
coroutine.resume(co);

end

but second "PrintString()" in co_main seem didn't run.
Kylotan
Kylotan
Well, in that case, it implies the problem is with your PrintString function, or how you're calling it, as you're seeing the issue before the coroutine even starts. You say there's a 'problem' running the coroutine line, but without saying what the problem is. Can't help there.
Rookie_Max
Rookie_Max
Thx, I got my code work now, thx for ur reply :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.