Search code examples
lua

LUA: does data lookup occur at the localized _G variable on the stack?


My apologies if the title to this question is a bit confusing. I could not find a better way to describe my question. I have always bashed my head against to wall to figure out this specific situation in lua.

Given the example below, will lua look for the function inside the localized variable on the stack or look for it in the hash part of the table? Take note that the global function is written as SomeGlobalFunc() instead of _G.SomeGlobalFunc()

--localize the global environment
local _G = _G

--run global func
SomeGlobalFunc()

Solution

  • The Lua manual says:

    _G is never used internally, so changing its value will affect only your own code

    This means all operations with _G do not affect Lua program behavior, except when you use this variable explicitly, such as _G.func()

    In other words, Lua knowns where the globals table is located without accessing variable _G

    P.S.
    Lua uses internally _ENV variable, not _G