How to declare a variable without initting it to nil in Lua?

10,617

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
Share:
10,617
user2206636
Author by

user2206636

Learning Blender. Active on reddit/blenderhelp, deviantart, learnmmd.com.

Updated on June 05, 2022

Comments

  • user2206636
    user2206636 almost 2 years

    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?

  • user2206636
    user2206636 about 11 years
    Thank for you answers. Actually, I was wondering because I wanted to test if "local limits the scope to one iteration" was true or not.
  • ChuckCottrill
    ChuckCottrill about 10 years
    Perl and Ruby both have a similar idiom using the '||' or operator, and so you see code such as, val||='default'; this value or default idiom is very useful.
  • Martin Ender
    Martin Ender about 10 years
    @ChuckCottrill Yup, you can do the same in JavaScript. Probably in most languages that have a concept of "truthy" and "falsy".