3 ms·
Every time you call make_counter() ... create_counter() If, local was the default, you would have: function create_counter(initial_val) count = i
by mangodrunk 14y ago
Every 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 14y 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)?