lua-users home
lua-l archive

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


Hey all,

I recently wrote a lua script which generates a C source file with a
binary symbol which includes the data of a given file.

I use it to roll a "predefined" lua script into my application at build
time. 

It works fine as long as I have it slurp up the ".lua" source file,
however, when I compile the lua file with luac, and then try to slurp it
up, it dosn't work. Not nearly enough characters are read out of the
binary file.

It looks to me like read("."); is having trouble... 

Is read() known to work with binary files?

Is read(".") the right way to get a single byte out of a binary file?

I've attached the bytecomp.lua script which turns a file into a C file
with a character string.


-- 
David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske@chat.net
-- bytecomp.lua
--
-- this byte compiles a string of bytes into a C data structure
--

-- write the preamble

write("/*\n"..
      " * <filename>\n" ..
      " *\n" ..
      " * this is an automatically generated binary file, don't mess with it!\n" ..
      " */\n");

write("\n\n\n");


-- write the octals

local data;
local octals_per_line = 9;
local cur_octal = 0;
local octal_count = 0;
local line_indent = "    ";


write("unsigned char bin_data[] = {\n".. line_indent);

data = read(".");
while (data) do
     write(format("0x%02X, ",ascii(data)));
     cur_octal = cur_octal + 1;
     octal_count = octal_count + 1;
     if (cur_octal >= octals_per_line) then
         cur_octal = 0;
         write("\n" .. line_indent);
     end
     data = read(".");
end;

-- write the last octal

write("0x00\n");

-- write the postamble

write("};\n\n");

write(format("unsigned int bin_len = %d;\n",octal_count));
write("\n\n");