why does
function inc()
x = x + 1
end
x = 0
inc()
print(x)
work, but
function inc()
x = x + 1
end
local x = 0
inc()
print(x)
not work
why does
function inc()
x = x + 1
end
x = 0
inc()
print(x)
work, but
function inc()
x = x + 1
end
local x = 0
inc()
print(x)
not work
You’re declaring the variable after the function. Declaring it local after the function which uses it will cause it to freak out. I recommend just doing f(x) for incrementing.
function inc(x)
return x + 1
end
local n = inc(0)
print(n)
But when doing what you’re asking, it’s probably best to either not declare it local or declare it local before the function.
local x = 0
function inc()
x = x + 1
end
inc()
print(x)
tl;dr: When inc
is parsed, x
is bound to the global ‘x
’ in both examples. The first example goes on to define a global ‘x
’, while the second does not.
Lua is a runtime-interpreted language. In other words, functions “don’t exist” until the interpreter reaches their declaration.
The interpreter runs line-by-line from the top of the file to the bottom.
When it sees a function, it creates a “closure” for that function, which binds any variables the function uses.
When a variable is bound, the closest-scoped version of that variable is used. If no local variables are available, the global scope is assumed.
So in both your examples, x
is being bound to the global scope, since the interpreter hasn’t “seen” a tighter-scoped x
yet. In the first one that’s OK because later you actually define a global x
.
In the second one, you define a local x
. That’s not going to work, because inc
has already been bound to the global.
You’ll note the error you get on your second one:
attempt to perform arithmetic on global 'x' (a nil value)
Because inc
is looking for a global x
, but it couldn’t find one.