lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Instead of starting your script with lua_dostring, try using loadstring/loadbuffer. This will push a function (the compiled string/script) onto the stack of your lua state.  You then call this function, executing the script, with lua_resume().  Your yield() and resume() should then work as expected.

You can also push arguments to this function if needed; these would be the nargs of the lua_resume.

Based on your code (but untested):

----
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

lua_State * L;

int add(lua_State * L)
{
int num_args = lua_gettop(L);
int i;
double sum = 0;


for (i = 1; i <= num_args; i++) {
sum += lua_tonumber(L, i);
}

lua_pushumber(L, sum); // need to push the result back on the stack

return lua_yield(L, 1); // 1 result
}

int main(int argc, char ** argv)
{
L = lua_open();
luaL_openlibs(L);
lua_register(L, "add", add);

luaL_loadstring(L, "print(add(3, 4, 5))"); // push a function, the compiled Lua code, on the stack
int result = lua_resume(L, 0); // call this function as a coroutine, passing in 0 arguments

// result may indicate script completion, script yield, or error:
if (result == 0) {
// script completed
// you can use the lua_State again if you want, but would need to push a new function on its stack first.
// but you can't resume it again until a new function is pushed on the stack
// for this example, I'll just exit
lua_close(L);
return 0;
} else if (result > LUA_YIELD) {
// there was an error
printf("error %s\n", lua_tostring(L, -1));
// the lua_State may now be corrupted, and should be closed
lua_close(L);
return 0;
}

// script yielded
// the lua State is yielded (just like coroutine.yield()), and can be resumed again.

// call lua_resume() once more; no need to push a function, since the previous function yielded:
int result = lua_resume(L, 0);

// again, you might want to check the result code of lua_resume, and handle in some way
// at this point, this example doesn't really make sense anymore, so I'll just close:

lua_close(L);
return 0;
}


Note that for this example (add(3, 4, 5)), a simple lua_getglobal and lua_pcall would have been sufficient, but I guess you wanted it for a more complex use-case...

On Jul 8, 2008, at 8:25 AM, Brandon wrote:

Thanks for the help, Raymond. I've looked into co-routines and
lua_newthread, and they don't look like what I want. I think I might be
on the wrong track with lua_yield and lua_resume.

I'm looking at the lua source code now. I think it should be possible
to do what I want, even if I have to manually modify the lua_State *.
I'll write back here if I figure it out.

If anybody is reading this and knows what to do, please don't hesitate
to write.

-Brandon


Be seeing you

grrr waaa
www.grahamwakefield.net