Optimizing Lua for looping

I execute my Lua script once per 10 ms program loop. using the same Lua_state (luaL_newstate, which is called once in my application)

The call to luaL_loadbuffer matches the script very closely, but it still seems like it doesnโ€™t need to be done every time the script is executed, since the script does not change.

I tried saving the binary using lua_dump () and then executed it, but lua_pcall () for some reason did not accept binary.

Any ideas on how to optimize? (LuaJIT is not a bad option here)

Jan

+6
source share
2 answers

You are right, if the code does not change, there is no reason to process the code. Perhaps you could do something like the following:

luaL_loadbuffer(state, buff, len, name); // TODO: check return value while (true) { // sleep 10ms lua_pushvalue(state, -1); // make another reference to the loaded chunk lua_call(state, 0, 0); } 

You will notice that we simply duplicate the function reference at the top of the stack, since lua_call removes the function that it calls from the stack. Thus, you will not lose the link to the downloaded piece.

+8
source

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 
+3
source

All Articles