lua-users home
lua-l archive

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


2008/6/21 Duck <duck@roaming.ath.cx>:
> Assume I have two modules, banana.lua and mango.lua, implemented in
> separate files which I require() separately. Assume that each module
> starts with a line like this:
>
>  module(...,package.seeall)
>
> If I simply concatenate the two files into, say, fruit.lua, and change the
> module() specifiers so they are like this:
>
>  module('banana',package.seeall)
>  -- rest of banana.lua
>
>  module('mango'),package.seeall)
>  --rest of mango.lua
>
> will I get identical results from "require(fruit)" as I used to get
> from "require('banana'); require('mango')"?

I think the best way to have the exact same result as seperate modules
is to use closure wrappers around the concatenated files, like Peter
Odding suggested, and to use the "preload" module searcher. Here is an
example :

package.preload.banana = function(...)
module('banana',package.seeall)
 -- rest of banana.lua
end

package.preload.mango = function(...)
 module('mango',package.seeall)
 --rest of mango.lua
end

-- rest of main program

You can write a Lua script to automate that. Here is a simple example
(not tested):

-- some help
if select('#', ...)<2 then
  print("usage: foo.lua <input script> [<module1> [<module2> [...]]]
<output script>
  os.exit(1)
end
-- build argument list
local args = {...}
-- open output file
local output = assert(io.open(args[#args]..".lua", "w"))
-- concatenate each module in the output
for i=2,#args-1 do
  -- load the module source
  local module = assert(assert(io.open(args[i]..".lua")):read"*a")
  -- create the function wrapper
  output:write('package.preload["'..args[i]..'"] = function(...)\n')
  -- put the module in it
  output:write(module)
  -- close the wrapper
  output:write('\nend\n')
end
-- append the main program to the end of the output
local program = assert(assert(io.open(args[1]..".lua")):read"*a")
output:write(program)