lua-users home
lua-l archive

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


Bonus challenge: Consider the following code with a "nonlocal" syntax:

x = 1
if condition() then
  x = 2
end
print(x)

Does it output 1 or 2? Compare this to the following:

I would say "2" if condition() is true, otherwise "1". The "x" is local because there is no "nonlocal" keyword.
 
local x = 1
if condition() then
  x = 2
end
print(x)

I would say same answer as before, but this is the explicit "local" case, while before it was local by default.
 
x = 1
if condition() then
  local x = 2
end
print(x)

This seems to be again the explicit "local" case. If there is no local x when you assign x = 1, then it will always print 1. Right?

x = 1
function shadow()
  if condition() then
    x = 2
  end
  print(x) -- this is definitely 2...
end
shadow()
print(x) -- but is this 1 or 2?

Why it should definitively print 2? if condition() is false x will never be assigned 2.

With global-by-default: the "x" in the shadow function references the "x" outside. Can print 1 or 2 depending on condition().

With local-by-default, if condition() is false the shadow function will print the "x" created outside, if condition() is true it will create a local x which is then printed. And this may be the case I was looking for. The difficult error to spot... right?

 
global x
The problem with this syntax is that you still need a local keyword within functions in order to avoid namespace collisions. 

Again I am not sure I understand. If it is local by default, why would you need a local keyword? 
By the way, "global" can be misleading indicating truly global variables. I would prefer to use "nonlocal" which indicates upvalue/global.

--
Andrea Vitali






_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org