I'm trying to compile a lua script that calls some exported functions, save the resulting bytecode to a file and then load this bytecode and execute it, but I haven't found any example on how to do this. Is there any example available on how to do this? How can I do this?
Edit: I'm using Lua + Luabind (C++)
Pre-compiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed.
Lua is not directly interpreted through a Lua file like other languages such as Python. Instead, it uses the Lua interpreter to compile a Lua file to bytecode. The Lua interpreter is written in ANSI C, making it highly portable and capable of running on a multitude of devices.
Instruction Summary Lua bytecode instructions are 32-bits in size. All instructions have an opcode in the first 6 bits. Instructions can have the following fields: 'A' : 8 bits 'B' : 9 bits 'C' : 9 bits 'Ax' : 26 bits ('A', 'B', and 'C' together) 'Bx' : 18 bits ('B' and 'C' together) 'sBx' : signed Bx.
This is all very simple.
First, you load the Lua script without executing it. It does not matter if you have connected the Lua state with your exported functions; all you're doing is compiling the script file.
You could use luaL_loadfile
, which uses C-standard library functions to read a file from disk and load it into the lua_State
. Alternatively, you can load the file yourself into a string and use luaL_loadstring
to load it into the lua_State
.
Both of these functions will emit return values and compiler errors as per the documentation for lua_load
.
If the compilation was successful, the lua_State
now has the compiled Lua chunk as a Lua function at the top of the stack. To get the compiled binary, you must use the lua_dump
function. It's rather complicated as it uses a callback interface to pass you data. See the documentation for details.
After that process, you have the compiled Lua byte code. Shove that into a file of your choice. Just remember: write it as binary, not with text translation.
When it comes time to load the byte code, all you need to do is... exactly what you did before. Well, almost. Lua has heuristics to detect that a "string" it is given is a Lua source string or byte code. So yes, you can load byte code with luaL_loadfile
just like before.
The difference is that you can't use luaL_loadstring
with byte code. That function expects a NULL-terminated string, which is bad. Byte code can have embedded NULL characters in it, which would screw everything up. So if you want to do the file IO yourself (because you're using a special filesystem or something), you have to use lua_load
directly (or luaL_loadbuffer
). Which also uses a callback interface like lua_dump
. So read up on how to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With