3 ms·
This discussion comes up on the mailing list occasionally. Well, the first answer to why we have global by default is history. Lua started out as a data descr
by ansible 15y ago
This discussion comes up on the mailing list occasionally.
Well, the first answer to why we have global by default is history. Lua started out as a data description where global by default was a convenience.
Local by default doesn't work so well either with nested scopes. Suppose we do have local by default and then consider this code:
x = 0
function a()
x = 1
function b()
print(x)
end
end
It is impossible to refer to a's x variable. This makes it harder to return a simple counter function, for example. This is regular Lua:
function create_counter(initial_val)
local count = initial_val or 0
local print_count = function() print (count) end
local increment = function() count = count + 1 end
return print_count, increment
end
Every time you call make_counter() you get a new pair of functions with their own internal count variable.
See also PEP 3104 for more: http://www.python.org/dev/peps/pep-3104/ http://www.python.org/dev/peps/pep-3104/
- mangodrunk 15y agoEvery time you call make_counter() ... create_counter() If, local was the default, you would have: function create_counter(initial_val) count = initial_val or 0 print_count = function() print (global count) end increment = function() global count = global count + 1 end return print_count, increment end Something like that, it doesn't seem that much worse. Also, why wouldn't the print_count function inherit the scope of the containing context so you wouldn't even have to have the "global" keyword. function create_counter(initial_val) count = initial_val or 0 print_count = function() print (count) end increment = function() count = count + 1 end return print_count, increment end
- ansible 15y ago... create_counter() ... That's what I get for writing code on a small phone screen. :-) function create_counter(initial_val) count = initial_val or 0 print_count = function() print (global count) end increment = function() global count = global count + 1 end return print_count, increment end You might not want to use 'global', because that implies global scope. And in this case, this is not what was intended. For Python, keywords like 'outer' or 'nonlocal' were proposed. All in all, I'd be OK with 'nothing by default', but I'm also OK with global by default as it is now. If accidental creation of globals is a problem I can use the 'strict' module. function create_counter(initial_val) count = initial_val or 0 print_count = function() print (count) end increment = function() count = count + 1 end return print_count, increment end If local was the default, wouldn't the assignment to count in increment() create a new local variable (which is then discarded)?