I have some lua scripts that are used many times. I don't want to use luaL_load every time I change between scripts. For example:
load script1
r开发者_C百科un script1
load script2
run script2
load script1
run script1
I want to keep a reference or something to script1 to be able to run it without loading it again. Is this possible? I'm new to lua and maybe this question is stupid... but for me is seems a good optimization to avoid loading a script if it is used often. I want that the above code to be turned in something like this:
load script1
load script2
set current script script1
run script1
set current script script2
run script2
set current script script1
run script1
Well, all you need to do is save the compiled chunk that luaL_loadfile
pushes on the stack. To do this, you can use lua_pushvalue(L,-1)
to make a copy of the compiled chunk at the top of the stack (because luaL_ref
will pop it), and int luaL_ref(L,LUA_REGISTRYINDEX)
to get a reference to it in the registry. Whenever you need the chunk you can use lua_rawgeti(L,LUA_REGISTRYINDEX, refToChunk)
, which will push the chunk back on the stack, ready for lua_call
ing it.
精彩评论