I needed to create a custom file format with embedded meta information. Instead of whipping up my own format I decide to just use Lua.
texture
{
format=GL_LUMINANCE_ALPHA;
type=GL_UNSIGNED_BYTE;
width=256;
height=128;
pixels=[[
<binary-data-here>]];
}
texture
is a function that takes a table as it sole argument. It then looks up the various parameter by name in the table and forward the call on to my C++ routine. Nothing out of the ordinary I hope.
Occasionally the files fail to parse with the following error:
my_file.lua:8: unexpected symbol near ']'
What's going on here?
Is there a better way to store binary data in Lua?
Update
It turns out that storing binary data is a lua string is non-trivial. But it is possible when taking care with 3 sequences.
Long string literals cannot have an embedded closing long bracket.
This one is pretty obvious.Long string literal cannot end with
]==
that matches the closing long bracket. This one is more subtle. Luckily the script will refuse to compile if you get this wrong.Cannot embed
\n
or\r
.
Lua's built in line-end processing messes these up. This problem is much more subtle. The script will compile fine but it will yield the wrong data. 0x13 replaced with 0x10, some 0x13's just missing.
To get around these limitation I split the binary data up then concat the various parts back together. I use a python script to generate output like this:
input:='XXXX\nXX]]XX\r\nXXXX]='
texture
{
format = RGB;
lg_width = 8;
lg_height = 7;
pixels= '' ..
[[XXXX]] ..
'\n' ..
[=[XX]]XX]=] ..
'\r\n' ..
[==[XXXX]=]==];
}