lua-users home
lua-l archive

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


On 1/8/06, Mihai Hanor <mhanor@yahoo.com> wrote:
> What is wrong with the next code?
> setfenv(0, { some_global_var = 0}
> print(_G.some_global_var)
>
> Or this one?
> t = { some_global_var = 0}
> setfenv(0, t)
> print(_G.some_global_var)
>
> Both return message errors like this one:
> lua: attempt to call a nil value
> stack traceback:
>         [C]: in function `print'
>         x.lua:2: in main chunk
>         [C]: ?
>
> I just want to add some global variable to the global enviroment.
After you replace an enviroment with new one (an empty, except one
variable) there is no more print function (which is actually is also a
global variable named "print" contataining the function).
For example, try this:
setfenv(1, { some_global_var = 2, print = print})
print(some_global_var)

Note that "_G" is just another table, so in example above, you can not
refer to the variable by name "_G.some_global_var". If you want to
inherit complete inviroment you can use metatable to setup the new
enviroment to look for non-existing values.

    local newgt = {}        -- create new environment
    setmetatable(newgt, {__index = _G})
    setfenv(1, newgt)    -- set it

Those technics are described in details in PIL: http://www.lua.org/pil/14.3.html

--
Best regards,
Zigmar