-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluaex.lua
57 lines (45 loc) · 1.08 KB
/
luaex.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
local gen_c = function(program)
local data = [=[#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main(int argc, char** argv) {
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
char data[]=]
.. #program .. "];\n"
local i = 0
for c in program:gmatch(".") do
data = data .. "data[" .. i .. "] = " .. string.byte(c) .. ";\n "
i = i + 1
end
data = data .. [=[
luaL_dostring(L, data);
lua_close(L);
return 0;
}]=]
return data
end
local compile_c = function(c_data, outfile)
local cfile_name = os.tmpname() .. ".c"
local cfile = io.open(cfile_name, "w")
cfile:write(c_data)
cfile:close()
os.execute("cc -o " .. tostring(outfile) .. " " .. tostring(cfile_name) .. " -Wall -I/usr/include/lua/5.1 -llua")
os.remove(cfile_name)
end
local outfile = arg[1]
if outfile == nil then
io.stderr:write("No file to process, quitting.")
os.exit(-1)
else
outfile=outfile:gsub("%.lua","")
end
local f = io.open(arg[1], "r")
local data = f:read("*all")
f:close()
if arg[2] == "c" then
print(gen_c(data))
else
compile_c(gen_c(data), outfile)
end