[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Embedding Lua bytecode in C binary
- From: "Mildred Ki'Lya" <ml.mildred593@...>
- Date: Thu, 27 Nov 2008 12:57:08 +0100
Hi,
Well, doing that is fairly simple. Recently, i had to create a binary
that would just invoke an internal lua script to do the job. I ended up
recreating bin2c:
---------- bin2c.lua ----------
local name, static = ...
name = name or "stdin"
static = static or ""
local out = { static, " ", "char ", name, "[] = {\n " }
if static == '' then
out[2] = ''
end
local len = 0
local c = io.read(1)
local l = 2;
while c do
len = len + 1
if l + 7 > 80 then
out[#out] = ",\n ";
l = 2
end
out[#out+1] = ("0x%02x"):format(c:byte())
out[#out+1] = ", "
l = l + 6
c = io.read(1)
end
out[#out] = " };\n\n";
out[#out+1] = "int "
out[#out+1] = name
out[#out+1] = "_size = "
out[#out+1] = tostring(len)
out[#out+1] = ";\n\n"
io.write(table.concat(out))
-------------------------------
Just invoke it that way:
lua bin2c.lua c_symbol [static] <input_file.lua >output_file.c
(if you add the optional static parameter, the byte array will be
declared static)
In your C file, you'll then be able to:
#include "output_file.c"
int err_code = luaL_loadbuffer(L, c_symbol, c_symbol_size, "input_file.lua");
That's really simple.
The only drawback is that require() would work like any script. So if
you use some modules, you'll have to include them as well (i guess
you'll need to put them in package.preload in the C code). But for what
I wanted to do, that wasn't necessary.
Mildred
--
Mildred Ki'Lya
╭───────── mildred593@online.fr ──────────
│ Jabber, GoogleTalk: <mildred@jabber.fr>
│ Site: <http://ki.lya.online.fr> GPG ID: 9A7D 2E2B
│ Fingerprint: 197C A7E6 645B 4299 6D37 684B 6F9D A8D6 9A7D 2E2B