lua-users home
lua-l archive

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


On Thursday 01, Valerio Schiavoni wrote:
> Hello everyone,
>
> consider the case where you *must* merge several Lua files and then
> execute the merged one.
> Which are the things to take care of? I've a couple of things in mind
> which I don't know how to solve:
>
> - name conflicts: files could have declared global variables with the
> same name; would it be enough to
>   make a re-write by for example prepending their name with the name
> of the file they are declared?
>
> - stack-trace line-numbers: if the merged file crashes, the
> stack-trace produces line-numbers of complete
>   non-sense to the developers of the original files...
>
>
> Do you have suggestions?

You could use the luac (lua compiler) to merge multiple lua files together.  
It will keep the line-numbers.  luac will also catch compile-time errors at 
compile-time instead of runtime.  If you want to do the whole thing in Lua 
code there is a version of luac written in Lua [1].  Local variables will 
stay local to each file, only globals would be shared.

To solve the global name conflicts, you can clear the global table between 
files.

Create two lua files:
-- setup_global_proxy.lua (code from Vaughan's post)
local old_G = _G
old_G.shared_state = {} -- a table for sharing state across files
_G = setmetatable( {}, old_G)

-- clear_globals.lua (code from Vaughan's post)
for k, v in pairs(_G) do
  _G[k] = nil
end

then compile your scripts like this
luac setup_global_proxy.lua a.lua clear_globals.lua b.lua \
  clear_globals.lua c.lua clear_globals.lua d.lua

If you need to send the merged script across the network, I would recommend 
first do a test compile on the server to catch errors, then send the text 
scripts across the network where they are merged before being executed (this 
is to get around sending Lua-bytecode across the network).

1. http://lua-users.org/lists/lua-l/2008-08/msg00092.html

-- 
Robert G. Jakabosky