How to declare a variable without initting it to nil in Lua?
declaration, local, lua, scope, variables
Solution
First off, the way `or` is defined in Lua gives you a nice idiom to avoid the `if` altogether:
variable = variable or value
If variable is `nil`, `or` will evaluate to its second operand. Of course, this will only work, if `false` is not a valid value for `variable` (because `false` and `nil` are both "false" as far as `or` is concerned).
However, you still have the problem that you need to declare the variable somewhere. I suppose your problem is that in the case of a global loop you think you have to do either:
while condition do
variable = variable or value
process(variable)
end
(which would make `variable` global) or
while condition do
local variable
variable = variable or value
process(variable)
end
which is pointless because `local` limits the scope to one iteration and reinitializes `variable` as `nil.
What you can do though is create another block that limits the scope of `local` variables but does nothing else:
do
local variable
while condition do
variable = variable or value
process(variable)
end
end
Problem
I've found it very useful to do something like: ``` if not variable then variable = value end ``` Of course, I'd usually rather that variable was local, but I can't declare it local in my if, or it won't be accessible. So sometimes I do: ``` local variable if not variable then variable = value end ``` The problem is that when I iterate over this code, the variable declaration sets the variable equal to nil. If I can live with a global value (I can), I can get around it by just not declaring the variable outside of the if block. But isn't there some way that I can both have my local value and let it keep its value?