lua-users home
lua-l archive

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


Hi,

Chunks in Lua are just normal functions. ie luaL_loadstring pushes an anonymous function which when run executes the code in the chunk. There's no need to recompile this function each time you intend on using it - just push it to the top of the stack each time you want to use it, followed by its arguments, then run it. Chunks are vararg functions by default, so there's not even any need to pass values via globals. Just pass them as parameters. Eg, your code could be roughly rewritten:

lua_State *L = luaL_newstate();
char* code =
 "local n = ... " /* give the first vararg a name, "n" */
 "return isPrime(n)";
luaL_loadstring(st, code); /* should check for compile errors here */
/* Stack: Chunk(function) */
for (int n = 2; n < N; ++n) {
 lua_pushnumber(L, n); /* push parameter n */
 /* Stack: Chunk(function), Number(n) */
 lua_pushvalue(L, -2); /* push the chunk to the top */
 /* Stack: Chunk(function), Number(n), Chunk(function) */
 lua_call(L, 1, 1); /* call the function, 1 parameter, 1 result */
 /* Stack: ?(Result) */
 /* do something with result */
 lua_pop(L, 1);
 /* Stack: */
}

Disclaimer: Code is completely untested and will likely not work nor even compile :).

- Alex

P.S. (confused as to why you're passing n as a string to IsPrime, guessing it's because it's just psuedocode)