lua-users home
lua-l archive

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


On Tue, Aug 25, 2015 at 9:53 PM, Nan Xiao <xiaonan830818@gmail.com> wrote:
> Hi all,
>
> I am a little confused about the following code in Pil:
>
>     i = 32
>     local i = 0
>     f = load("i = i + 1; print(i)")
>     g = function () i = i + 1; print(i) end
>     f() --> 33
>     g() --> 1
>
> Why does function g() always get local i, not global i? If function
> g() wants to
> get the global i, how does it do?
>
> Thanks in advance!

g() gets the local because locals automatically trump globals of the
same name. Functions produced by load() can't see locals, hence why
f() gets the global i.

To force access to the global instead of the local, index the _G table:

    -- Consider this an extension of the example code above
    h = function () _G.i = _G.i + 1; print(_G.i) end
    h() --> 34

_G is the global environment, essentially a table of all global
variables. It behaves as an ordinary table, so you can index it,
iterate over it, set a metatable for it (useful for preventing
accidental globals meant to be local), and other things just like a
real table.