lua-users home
lua-l archive

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

2008/6/21 Duck <>:
> 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(...)
 -- rest of banana.lua
end = function(...)
 --rest of mango.lua

-- 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>
-- build argument list
local args = {...}
-- open output file
local output = assert([#args]..".lua", "w"))
-- concatenate each module in the output
for i=2,#args-1 do
  -- load the module source
  local module = assert(assert([i]..".lua")):read"*a")
  -- create the function wrapper
  output:write('package.preload["'..args[i]..'"] = function(...)\n')
  -- put the module in it
  -- close the wrapper
-- append the main program to the end of the output
local program = assert(assert([1]..".lua")):read"*a")