lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Jun 28, 2014, at 6:39 AM, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:

>> how I handle such things is to use a simple program that converts the
>> Lua script into a C character array like:
> 
> I use this:
> 	xxd -i foo.lua | sed 's/unsigned/static const unsigned/' > foo.h
> 
> Then foo.h contains this:
> 
> 	static const unsigned char foo_lua[] = {
> 		...
> 	};
> 	static const unsigned int foo_lua_len = 403;
> 
> which you can use to call luaL_loadbuffer.
> 

One problem we had with this approach is limitations from some C compilers about the maximum number of elements allowed in the initializer. In the end, we settled on a hybrid approach of using an array of (string, length) tuples, with the strings escaped for non-ASCII characters. Something like:

typedef struct tagBinBlock {
	npint nSize;
	npchar *sData;	
} BinBlock;

static BinBlock g_aBoundLuaBoot[] = {
	{	14,	"print('POP!')\n"						},
	{	0,	NULL									}
};

Of course, the strings can contain embedded zeroes, hence the explicit size, and this design requires a custom encoder and a (quite simple) decoder. It also means the loaded Lua code is present in memory both in the above form and a raw concatenated form, but it does allow much larger scripts to be embedded regardless of C compiler. We limit each string to 256 bytes, which gives us a much larger maximum size for statically embedded Lua code (source or compiled).

—Tim