lua-users home
lua-l archive

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


Hi,

Björn De Meyer:
> function safeload(filename, glob)
> local act
> glob = glob or getglobals()
> act = function()
>       local f, e
>       f, e = loadfile(filename)
>       if f then return f()
>       else return nil, e end
>       end
> setglobals(act,glob)
> return act()
> end

This is getting confusing...  I expected this to _still_ ignore the glob
argument (because loadfile has its own globals) but it works!  It turns out
that "loadfile" and "loadstring" (and only these?) perform a special trick:
they revert to the globals of the _calling function_ instead of using their
own (pulled off through the debug interface)!  So "loadfile(a)()" is _not_
equivalent with "dofile(a)":

sb = {dofile=dofile, loadfile=loadfile, print=print}
setglobals(nil, sb)

-- Note: file "incl.lua" contains the line "a = 1"

dofile "incl.lua"
print(a)  -- prints "nil"

loadfile "incl.lua" ()
print(a)  -- prints "1"

Op top of this, "require" behaves as "dofile" in this respect.  This inspite
of the fact that require internally uses loadfile(file)() to execute the
file...  (but not the loadfile from the baselib...)

Suggestion: let require call luaB_loadfile (the baselib one) instead of
luaL_loadfile.  Or will this mess up something else??

Bye,
Wim