lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



> No, because when you compile 3 Lua files together, luac fixes things so that
> when you run the precompiled code it executes all three files.

> Try luac -l prog1.lua prog2.lua prog3.lua and see the main function.

> Now, there is no real reason for this being as it is. It's just the simplest
> thing that is compatible with the old idea of dofile, before the loadfile days.
> If someone can argue that having different options for luac to select what to
> do in the created main, it can be done, but I don't think it'll be easy to come
> up with something simple that is consistent with the case of 1 file.

Since it is easy enough to write luac in lua, I don't see the point of changing
it. Jose could simply do the following: (untested code, Unix dependency)
(TODO: parse options for -o)

local chunk = [[
local MODULE = {}
]]

for i = 1, args.n do
  local filename = args[i]
  -- path/to/file/enemy.lua => enemy
  local basename = string.gsub(string.gsub(filename, ".*/", ""), "%..*", "")
  -- verify that it is a valid name
  assert(string.find(basename, "^[%a_][%w_]*$"))
  -- upcase the first character to avoid reserved words
  string.gsub(basename, "^%l", string.upper)
  -- get the actual contents of the file
  local file = assert(io.open(filename, "r"))
  local func = file:read"*a"
  file:close()
  -- make sure it compiles
  assert(loadstring(func, filename))
  -- add it to the template
  chunk = chunk .. [[
function MODULE.]] .. basename .. [[()
]] .. func .. [[
end
]]
end

-- arrange for the chunk to return its table
chunk = chunk .. [[
return MODULE
]]

-- compile the chunk and dump it to output.dat
local compiled = assert(string.dump(assert(loadstring(chunk, "merged file")))
local file = assert(io.open("output.dat", "wb"))
file:write(compiled)
file:close()

------ To use the resulting file:

local E = assert(loadfile"output.dat")()
E.Enemy1()

------ or even
setmetatable(_G, {__index = assert(loadfile"output.dat")())
Enemy1()