3

I am using the Lua "C" API function luaL_loadbuffer() to run Lua code.

I have a small handful of Lua chunks that I am calling many, many times. But every time I call luaL_loadbuffer() the chunk gets recompiled. This seems hugely inefficient. Most of the code referenced by the chunk is precompiled, but why do I need to recompile the chunk itself every time? How can I avoid this recompilation?

Can I pass a precompiled chunk to luaL_loadbuffer()?

Can I make a full copy of the returned Lua stack and re-use it?

Is there some other clever approach?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
the.jxc
  • 3,373
  • 21
  • 21
  • 2
    The returned chunk **is** your compiled code. If you want to run it more than once save it and run it again later. Not the stack, the returned chunk itself. – Etan Reisner Jan 07 '15 at 22:51
  • By "returned chunk" you mean the one that is on the stack yes? Can I store that an use it on a new (clean) LUA stack? Or do I need to use the same stack but just make sure I pop everything off it and push that chunk back on? – the.jxc Jan 07 '15 at 23:09
  • 1
    Yes, the one on the stack. No, you cannot migrate it to another lua_State. Yes, you can save it in the same lua_State and use it again later. That's lua_State not stack. The (current) stack is a transient thing much of the time. The lua_State is not. – Etan Reisner Jan 08 '15 at 00:37

2 Answers2

2

Continue to use luaL_loadbuffer to load scripts. Load here means precompile. Just save the function left on the stack somewhere in your program (or leave it on the stack if you can). When the time comes to run a script, lua_pushvalue and lua_pcall it.

lhf
  • 70,581
  • 9
  • 108
  • 149
1

Use luaL_loadstring to load the binary chunk you've precompiled with luac. But beware - those binaries are not portable across platforms or Lua versions.

greatwolf
  • 20,287
  • 13
  • 71
  • 105
BadZen
  • 4,083
  • 2
  • 25
  • 48
  • D'oh! Yes indeed! lua_load says this should be possible. Of course, next question is how do I compile code without using luac (i.e. without having to write my chunk to disk and executing a fork to a subprocess since that's all yucky and a bit fragile). – the.jxc Jan 07 '15 at 22:55
  • If you don't want to use luac, load the source instead, and dump the function object with lua_dump(). It will give you (almost) the same result - you'll have to set the chunk name, etc when you load it back. – BadZen Jan 07 '15 at 22:59
  • That sounds suitably tricksy! Any chance of a link to an example code fragment? – the.jxc Jan 07 '15 at 23:01
  • 4
    Use `luaL_loadbuffer`, *not* `luaL_loadstring`, because `luaL_loadstring` assumes a zero-ended string. – lhf Jan 07 '15 at 23:59