-- Usage: -- lua auto.lua .. -- -- Example: -- lua auto.lua boot graphics local max_width = 18 local pattern = [[ // [%s] const char %s[] = { %s }; // [%s] ]] --formatting parameters: -- - input file name -- - c variable name -- - array contents -- - input file name function auto(name) --the input file name local src = name .. ".lua" --and the output one local dst = name .. ".lua.h" --the name of the variable local cpp_name = name .. "_lua" --do a minimal code check --(syntax errors, really) loadfile(src) --no error catching? no --we have the main loop doing that for us --what character is this on this line? local counter = 0 local function tohex(c) counter = counter + 1 --if we've reached the maximum width (or 0) --then we'll carry on and add a newline if counter % max_width == 0 then return ("\n\t0x%02x, "):format(c:byte()) end --otherwise we just use the hex of the current byte return ("0x%02x, "):format(c:byte()) end --let's open the input file local src_file = io.open(src, "rb") --create an output string local out_data = "" --go through the input file line-by-line for line in src_file:lines() do --if the line is non-empty if #line > 0 then --set the counter to -1 --this will start a new line (see tohex) counter = -1 --append the output to what we had, plus a newline character (0x0a is newline) out_data = ("%s%s0x0a,"):format(out_data, line:gsub("\r", ""):gsub(".", tohex)) end end --close our input src_file:close() --open, write and close the output out_file = io.open(dst, "wb") --see pattern above out_file:write(pattern:format(src, cpp_name, out_data, src)) out_file:close() --tell the world we succeeded! print(name .. ": Success") end --usage if #arg == 0 then return print("Usage: lua auto.lua .. ") end --the 'main' procedure for i, v in ipairs(arg) do --run the auto function for every argument --but do it with pcall, to catch errors v = v:gsub("%.lua$", ""):gsub("^(.+)/", "") -- normalize input local ok, err = pcall(auto, v) if not ok then --inform people we've failed print(v .. ": " .. err) end end