将 lua-bytecode-string 嵌入 C/C++ 源文件

如何在 C/C++ 文件中包含 lua-bytecode-string?

$ luac -o test -s test.lua
$ cat test
LuaS�

xV(w@@A@$@&�printTestj

现在,如果您可以将此字节串插入到 C/C++ 文件中,您实际上可以

luaL_loadfile(lua, bytestring.c_str());

这样就没有必要在运行时加载 test.lua。您甚至不必在运行时解释 test.lua,不是吗?

更新:

此问题的前两个评论有助于生成字节串,以便您可以将其包含在 C/C++ 代码中。 来自这个答案 的思路如下:

xxd -i test > test.h

这将创建以下内容:

unsigned char test[] = {
  0x1b, 0x4c, 0x75, 0x61, 0x53, 0x00, 0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a,
  0x04, 0x08, 0x04, 0x08, 0x08, 0x78, 0x56, 0x00, /* ... */, 0x00};
unsigned int test_len = 105;

这很好用,但是这不会在 luaL_loadstring 中起作用,因为

该函数使用 lua_load 来加载零终止的字符串 s 中的块。

注意:在 test 中有数据是 _零_。

点赞
用户107090
用户107090

使用 luaL_loadbuffer 代替 luaL_loadstring

luaL_loadbuffer(L,test,test_len,"");
2019-03-13 13:01:50