编译lua代码,存储字节码然后加载执行
我正在尝试编译一个调用一些导出函数的 lua 脚本,将生成的字节码保存到一个文件中,然后加载这个字节码并执行它,但我还没有找到任何关于如何执行此操作的示例.有没有关于如何做到这一点的例子?我该怎么做?
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?
我正在使用 Lua + Luabind (C++)
I'm using Lua + Luabind (C++)
推荐答案
这一切都很简单.
首先,您加载 Lua 脚本, 不执行它.是否已将 Lua 状态与导出的函数连接起来并不重要;您所做的就是编译脚本文件.
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.
您可以使用luaL_loadfile
,它使用C 标准库函数从磁盘读取文件并将其加载到lua_State
.或者,您可以自己将文件加载到字符串中,然后使用 luaL_loadstring
将其加载到 lua_State
中.
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
.
这两个函数都会根据 文档发出返回值和编译器错误对于 lua_load
.
Both of these functions will emit return values and compiler errors as per the documentation for lua_load
.
如果编译成功,lua_State
现在将编译后的 Lua 块作为 Lua 函数放在栈顶.要获得编译后的二进制文件,您必须使用 lua_dump
函数.它相当复杂,因为它使用回调接口来传递数据.请参阅文档了解详情.
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.
在这个过程之后,你就有了编译好的 Lua 字节码.将其推入您选择的文件中.请记住:将其写为二进制,而不是文本翻译.
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.
到了加载字节码的时候,您所需要做的就是... 完全按照您之前所做的.嗯,差不多.Lua 具有启发式方法来检测字符串"是否存在.它是一个 Lua 源字符串或字节码.所以是的,您可以像以前一样使用 luaL_loadfile
加载字节码.
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.
区别在于您不能将 luaL_loadstring
与字节码一起使用.该函数需要一个以 NULL 结尾的字符串,这很糟糕.字节码可以在其中嵌入 NULL 字符,这会搞砸一切.所以如果你想自己做文件IO(因为你使用的是特殊的文件系统什么的),你必须直接使用lua_load
(或luaL_loadbuffer
).它还使用了一个回调接口,比如 lua_dump
.所以阅读如何使用它.
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.
相关文章