1

How do you include a lua-bytecode-string into a C/C++ file ?

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

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

Now if you could insert this byte-string into a C/C++-file, you could actually

luaL_loadfile(lua, bytestring.c_str());

which makes it unnecessary to load test.lua at run-time. You would not even have to interpret test.lua at run-time, right?

Update:

The first two comments to this question were helpful for generating a bytestring so that you can include it in your C/C++ code. From this answer I got this idea:

xxd -i test > test.h

which creates this:

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;

This is great, but this will not work with luaL_loadstring, since

This function uses lua_load to load the chunk in the zero-terminated string s.

Note: there are zeros as data in test.

user1511417
  • 1,880
  • 3
  • 20
  • 41
  • 1
    Possible duplicate of [Embedding resources in executable using GCC](https://stackoverflow.com/questions/4158900/embedding-resources-in-executable-using-gcc) – Botje Mar 13 '19 at 10:53
  • 1
    lua does not need to convert the code to byte code but the bytecode still needs to be interpreted – gotocoffee Mar 13 '19 at 10:58
  • 1
    `(luaL_loadbuffer(L, s, length_of_s, s) || lua_pcall(L, 0, LUA_MULTRET, 0))` should do the job – gotocoffee Mar 13 '19 at 13:02

1 Answers1

4

Use luaL_loadbuffer instead of luaL_loadstring:

luaL_loadbuffer(L,test,test_len,"");
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks, but this will not work either, since `test` contains dec.-values which are greater than `125` . See question: `unsigned char[]`. This is why it's an array of unsigned chars. The problem here is, that `luaL_loadbuffer` expects an `const signed char-Pointer`, which is interesting. – user1511417 Mar 13 '19 at 13:37
  • 1
    @user1511417 `luaL_loadbuffer(L,(const char*)test,test_len,"");` – gotocoffee Mar 13 '19 at 13:45
  • This should generate a warning, which should be taken seriously. – user1511417 Mar 13 '19 at 13:54
  • I've just tested gotocoffee's suggestion. It works, but why? :D – user1511417 Mar 21 '19 at 13:51