lua-users home
lua-l archive

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


On Fri, Jul 2, 2010 at 3:46 AM, Valerio Schiavoni
<valerio.schiavoni@gmail.com> 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:

You can also do several loadstrings in sequence:

loadstring( [=====[
foo = bar
print'ok'
]=====], '=a.lua' )()

loadstring( [=====[
local foo = bar
]=====], '=b.lua' )()


And so on... This way you will preserve local line numbers, although
your stacktrace will have one more level (the main file chunk, that
is).

To avoid global namespace clash, you can create a loadstring_sandbox,
along the lines of:

loadstring_sandbox = function( str, name )
    local fn, err = loadstring( str, name )
    if not fn then return fn, err end
    local env = setmetatable( {}, { __index = _G } )
    setfenv( fn, env )
    return fn
end

Thus:

loadstring_sandbox( [=====[
foo = bar
print'ok'
]=====], '=a.lua' )()

loadstring_sandbox( [=====[
local foo = 42
print(foo)
]=====], '=b.lua' )()


Of course this code wasn't tested :)

--rb