Lua Compiler In Lua

lua-users home
wiki

The standard Lua compiler [luac.c] is a C program included with the Lua distribution. However, it is possible to compile a Lua script using only the standard interpreter:

lua -e 'io.write(string.dump(assert(loadfile())))' <sample.lua >sample.out

If you want to emulate the behavior of luac when given multiple input files:

-- compile the input file(s)
local chunk = {}
for _, file in ipairs(arg) do
  chunk[#chunk + 1] = assert(loadfile(file))
end

if #chunk == 1 then
  chunk = chunk[1]
else
  -- combine multiple input files into a single chunk
  for i, func in ipairs(chunk) do
    chunk[i] = ("%sloadstring%q(...);"):format(
      i==#chunk and "return " or " ",
      string.dump(func))
  end
  chunk = assert(loadstring(table.concat(chunk)))
end

local out = assert(io.open("luac.lua.out", "wb"))
out:write(string.dump(chunk))
out:close()

Note this doesn't support any of luac's options (-l, -p, etc) and it writes its output to luac.lua.out instead of luac.out.

See Also


FindPage · RecentChanges · preferences
edit · history
Last edited May 28, 2007 8:02 pm GMT (diff)