Skip to content

Instantly share code, notes, and snippets.

@armornick
Created April 21, 2014 13:25
Show Gist options
  • Save armornick/11142696 to your computer and use it in GitHub Desktop.
Save armornick/11142696 to your computer and use it in GitHub Desktop.
Utility to convert lua scripts to a C character array to embed scripts in code
---
-- Code copied from Premake-stable (scripts/embed.lua)
---
function iif(cond, iftrue, iffalse)
if cond then return iftrue else return iffalse end
end
local function stripfile(fname)
local f = io.open(fname)
local s = assert(f:read("*a"))
f:close()
-- strip tabs
s = s:gsub("[\t]", "")
-- strip any CRs
s = s:gsub("[\r]", "")
-- strip out comments
s = s:gsub("\n%-%-[^\n]*", "")
-- escape backslashes
s = s:gsub("\\", "\\\\")
-- strip duplicate line feeds
s = s:gsub("\n+", "\n")
-- strip out leading comments
s = s:gsub("^%-%-\n", "")
-- escape line feeds
s = s:gsub("\n", "\\n")
-- escape double quote marks
s = s:gsub("\"", "\\\"")
return s
end
local function writeline(out, s, continues)
out:write("\t\"")
out:write(s)
-- out:write(iif(continues, "\"\n", "\",\n"))
out:write("\"\n")
end
local function writefile(out, fname, contents)
local max = 1024
out:write("\t/* " .. fname .. " */\n")
-- break up large strings to fit in Visual Studio's string length limit
local start = 1
local len = contents:len()
while start <= len do
local n = len - start
if n > max then n = max end
local finish = start + n
-- make sure I don't cut an escape sequence
while contents:sub(finish, finish) == "\\" do
finish = finish - 1
end
writeline(out, contents:sub(start, finish), finish < len)
start = finish + 1
end
out:write("\n")
end
local function embed(fn, out)
out = out or io.open(fn..".c", "w+")
if out then
local arrname = fn:gsub("%.", "_")
out:write(string.format("const char %s[] = ", arrname))
local s = stripfile(fn)
writefile(out, fn, s)
out:write(";")
end
out:close()
end
embed("parser.lua")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment