I wrote this little Lua script to convert a binary file into a Lua string. This is handy if you want to put PCM sound data in your app, etc.
To use this script copy the code below, and save it to a file named BString.lua (or anything you like), and mark it as executable by issuing the following command line:
chmod +x BString.lua
Now if you wanted to convert a binary file named “HelloWorld.wav” to a string named “hw” in a file named “Sound.lua” then you would write:
./BString.lua HelloWorld.wav Sound.lua hw
Right now it is using string concatenation which isn’t as efficient to load at runtime as other approaches. I will update it later. But I though I would post it now since it is handy
The Script:
#!/usr/bin/env lua
-- Check the command line
if #arg < 1 then
print("Usage: " .. arg[0] .. " inFile [outFile] [stringName]");
return;
end
-- Get the in and out filenames
inFName = arg[1];
outFName = arg[2] or (arg[1] .. ".out");
sName = arg[3] or "foo"
-- Read the data
inFile = io.open(inFName, "r");
if not inFile then
print("Error reading " .. inFName);
return;
end
data = inFile:read("*all");
inFile:close();
-- Write the binary string
outFile = io.open(outFName, "w+");
newLinePrefix = sName .. ' = ' .. sName .. ' .. "';
outFile:write(sName .. ' = ""\
');
outFile:write(newLinePrefix);
for pos = 1, #data do
if pos % 10 == 0 then
outFile:write('"\
');
outFile:write(newLinePrefix);
end
b = string.byte(data, pos);
outFile:write(string.format("\\\\%i", b));
end
outFile:write('"\
');
outFile:close();