Skip to content

Instantly share code, notes, and snippets.

@stevedonovan
Created May 25, 2012 10:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevedonovan/2787105 to your computer and use it in GitHub Desktop.
Save stevedonovan/2787105 to your computer and use it in GitHub Desktop.
A Lua script to embed Lua code in a C module.
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
static const char * lua_code = \
"module 'foo'\n"\
"\n"\
"function answer()\n"\
"return 42\n"\
"end\n";
EXPORT int luaopen_foo (lua_State *L) {
luaL_dostring(L,lua_code);
return 1;
}
-- lua2c.lua
function quit (msg)
io.stderr:write(msg,'\n')
os.exit(1)
end
function massage_path (name)
return (name:gsub('%.','/'))
end
function massage_name (name)
return (name:gsub('%.','_'))
end
local skeleton = [[
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
$CODE;
EXPORT int luaopen_$NAME (lua_State *L) {
luaL_dostring(L,lua_code);
return 1;
}
]]
local name = arg[1] or quit 'must provide name of module'
local file = massage_path(name) .. '.lua'
local f,e = io.open(file,'r')
if not f then quit (e) end
local out, append = {}, table.insert
append(out,'static const char * lua_code = ')
for line in f:lines() do
-- all non-blank, non-comment lines
if not line:match '^%s*%-%-' or line:match '^%s*$' then
line = line:gsub('^%s*',''):gsub('\\','\\\\'):gsub('"','\\"')
line = '"'..line..'\\n"'
append(out,line)
end
end
f:close()
out = table.concat(out,'\\\n')
local output = skeleton:gsub('%$(%u+)',{
CODE = out,
NAME = massage_name(name)
})
f = io.open(massage_path(name)..'.c','w')
f:write(output)
f:close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment