JohnBig
JohnBig

Reputation: 207

Lua: Do I need to repeat variable in if?

When I say if var == "one" or var == "two" or var == "three" or var == "four" then and the var is always the same, can I shorten this somehow, like if var == "one" or "two" or "three" or"four" then

Do I have to use parenthesis?

Upvotes: 2

Views: 166

Answers (2)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39400

The Lua's if statement expects a singular value. That value gets converted to boolean true and false values that determine the if behavior.

So, in other words, you can imagine your if like this:

condition = var == "one" or var == "two" or var == "three" or var == "four"
if condition then
    --...
end

So if doesn't help us with the repetition itself, but knowing what it expects, it's easy to create a helper function. We can make it take a value and a list of values, compare it to the values, and return true if there's any match. This is, incidentally, the same as checking if a list contains a specific element, which is easier to search for.

So, given such a simple helper:

function contains(t, x)
    for _, v in ipairs(t) do
        if v == x then
            return true
        end
    end

    return false
end

We can write your if like so:

if contains({"one", "two", "three", "four"}, var) then
    --...
end

Upvotes: 1

Jasmijn
Jasmijn

Reputation: 10477

We can take advantage of tables. In particular, if some_table doesn't contain some_key, then some_table[some_key] returns nil, which is falsy.

For example:

if ({one=1, two=1, three=1, four=1})[var] then

I've used 1 because it's short to type, but you can use any value except nil or false, as those two are the only falsy values in Lua.

This creates a new table every time the condition is evaluated, so if you want to check it frequently (in a tight loop, for example), it may be worth it to create the table outside the loop:

local CONDITION = {one=1, two=1, three=1, four=1}
...
   -- inside a loop:
   if CONDITION[var] then

Upvotes: 5

Related Questions