I am trying to understand the rational for global by default and explicit local - I have been reading the lua wiki, lua archive, and all I could find on the topic
I have seen that other languages have had similar discussion, in Python for example the proposal is to keep the local by default and use the "nonlocal" keyword
now coming to Lua let's make an example copying from the nice article "why explicit local is a good thing" - I highlight in capital letter the keyword which is subject of the discussion
---- explicit local
LOCAL function getnums()
-- implementation omitted
end
loop:addtimer(1000, function()
LOCAL nums = getnums()
LOCAL square_sum = 0
nums:each(function(num)
LOCAL square = num*num
square_sum = square_sum + square
end)
print(square_sum)
end)
---- explicit nonlocal
function getnums()
-- implementation omitted
end
loop:addtimer(1000, function()
nums = getnums()
square_sum = 0
nums:each(function(num)
square = num*num
NONLOCAL square_sum = square_sum + square
end)
print(square_sum)
end)
so it seems that local by default could be done - is there any real advantage in using LOCAL instead of NONLOCAL?
I am thinking about what happen when one omits the keyword; or thinking about what happens if one does not take into account declarations in enclosing scopes
from a very broad point of view, when explicit LOCAL is used:
local x = 1 -- always assign to local
x = 1 -- maybe local, upvalue, global; it is global if x does not exist
_ENV.x = 1 -- always global
when explicit NONLOCAL is used
x = 1 -- always assign to local
nonlocal x = 1 -- maybe upvalue or global; it is global if x does not exist
_ENV.x = 1 -- always global
when referencing x in a formula nothing changes: x can be local, upvalue if no local is found with the sam enam, or global if no local and no upvalue has the same name.
I take the opportunity to ask another question weakly related to this: I have been reading one of the design flaws in Lua is the fact that referencing variables that do not exist simply returns nil and no error is thrown
but this seems to be wrong because if it is does not exist, when it is referenced the global environment is seached, and access to the global environment can be monitored by metamethods, that is strict.lua - am I right?
Andrea