Strogg
Strogg

Reputation: 31

What does this mean in Lua? "var = var or"

Could you please tell what does this mean? I know about basic variable declaration and assigment, but this is confusing. What the difference between this

var = var or {
        "one",
        "two",
        "three",
    }

and

var = { "one",
        "two",
        "three",
    }

I quickly checked manual and could not find explanation.

Upvotes: 2

Views: 1350

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26559

or doesn't return a boolean; rather, it returns either the first truthy value or the last falsey value if none of them are true.

For example:

print(nil or 123) -- 123
print(123 or nil) -- 123
print(456 or 123) -- 456
print(nil or false or "hi") -- hi

The line you found is an idiomatic use of this property for setting a variable to a default value if it's nil or false, but keeping its value if it's anything else. Example

function foo(arg)
    arg = arg or "hello world!"
    print(arg)
end

foo() -- "hello world!"
foo("goodbye world!") -- "goodbye world!"

and works similarly as well; it returns either the first falsey value or the last truthy value. By using the two together, you can also emulate the ternary operator:

function foo(bool)
    print(bool and "yes" or "no") -- second value (the true value) must be truthy
end
print(foo(true)) -- "yes"
print(foo(false)) -- "no"
print(foo(123)) -- "yes"

Upvotes: 7

Related Questions