3 ms·
... create_counter() ... That's what I get for writing code on a small phone screen. :-) function create_counter(initial_val) count = initial_val or
by 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)?