lua-users home
lua-l archive

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


I disagree with this article: Lua has NO such "global" variables. All variables are scoped within some "local" environment; adding the "\" does not allow distinguish which other environment will be used if it's not the top-level local environment. All variables are in fact resolved in a stacked chain of environments, until one has an accessor to resolve it or the variable is part of its local associative table.
The correct way to forbid th incorrectly named "globals" is to define an accessor in the local environment that will resolve all non-locally defined variables and will block the lookup looping into the upward environments.

Generally this is done as part of the upward environment that instanciates the local environment to "sandbox" it so that it cannot modify the upward environment (such thing is done for example in interactive Lua consoles). But Lua has tons of usages where a function may need to modify the enclosing environment: Lua is not purely a "functional language" where all varaibles are resolved locally and the only way to pass a value to the caller is by return values that the upward environemnt will accept ot reject. If everything becomes local by default, you transform imperatively Lua into a functional language (and this has performance consequences as all callers must manage the copies of all return values if appropriate). But Lua can be considered a functional language if we just consider the stack of environments as an additional parameter of every function call (except that this parameter is hidden and programmers do not properly manage this hidden parameter and its real effect).

There are solutions to this problem: a Lua script can start by a "require('NoGlobal'); whcih will define the write accessor inside the local environment to block the variable lookup chain, and will instead throw an error). With such solution, we never need any new tricky syntax with "\" (and in fact it will not even work, given that this "\" does not indicate which other environment to use for this pseudo-global variable assignment (it's not necessarily the immediate parent environment, it may be any accessible ancestor that will honor the new assignment request oir reject it instead of chaining to another parent).

Le ven. 15 mai 2020 à 15:14, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> a écrit :
See this thread: http://lua-users.org/lists/lua-l/2018-07/msg00422.html

For a patch to play with global decoration of variables, see
http://lua-users.org/lists/lua-l/2018-07/msg00430.html
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org