Running loadbuffer compiles the script into a piece of lua code, which can be thought of as an anonymous function. The function is placed on the top of the stack. You can โsaveโ it like any other value in Lua: push the function name onto the stack, then call lua_setglobal (L, name). After that, every time you want to call your function (piece), you push it onto the Lua stack, insert the parameters into the stack, and call lua_pcall (L, nargs, nresults). Lua will push this function and push the results of nresults onto the stack (no matter how many results your function returns), if more are returned, they are discarded if their number is less than zero). Example:
int stat = luaL_loadbuffer(L, scriptBuffer, scriptLen, scriptName); // check status, if ok save it, else handle error if (stat == 0) lua_setglobal(L, scriptName); ... // re-use later: lua_getglobal(L, scriptName); lua_pushinteger(L, 123); stat = lua_pcall(L, 1, 1, 0); // check status, if ok get the result off the stack
source share