lua-users home
lua-l archive

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



> On Nov 12, 2018, at 10:00 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 
> Global variables?
> 
> Well, of course there is no such thing. The manuall tells us so.
> "The Lua library is fully reentrant: it has no global variables."
> And as we all know, what looks like a global variable 'var' in a Lua
> 5.2 or 5.3 script is just syntactic sugar for '_ENV.var'.
> 
> The API nevertheless talks like there are global variables:
> 
> int lua_getglobal (lua_State *L, const char *name);
>   Pushes onto the stack the value of the global 'name'. Returns the
> type of that value.
> 
> Are these globals the same thing as global variables in a Lua script?
> 
> Let's see. These refer to table entries in "the global environment
> stored at index LUA_RIDX_GLOBALS in the registry". (RIDX means
> registry index).
> 
> So they are the same if and only tf "the global environment" is the
> same as _ENV. This is the case when you start up Lua, but if you
> fiddle around with _ENV, it does not mean that "the global
> environment" is different too, only that you can no longer see it
> (unless of course you were prudent enough to have stored _G in a local
> variable).
> 
> So is 'lua_getglobal' exposed at the Lua level? In other words, is
> there anything you can do to retrieve an original global variable if
> _ENV has changed? Obviously you can if you copied over either _G or
> the debug library. Any other way?
> 

Or, for “lua_getglobal()” read “lua_getfromdistinguishedenvironment()”.

—Tim