Ask Your Question
0

lua concat "and" and "or" statements

asked 2021-03-04 12:47:22 +0000

Hello there!

Let's say I have an if-statement, i.e.

if a == 0 and (b == 1 or b == 3 or b == 5) then output = "ok"

Is there a way to shorten the code like this: if a == 0 and (b == 1, 3, 5) then output = "ok"

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-02 16:33:49 +0000

dd4235 gravatar image

There is not a way to shorten your code to get that. They way you have it is idiomatic and (in my opinion) easy to read.

Here are a couple of options for longer, worse, and (probably) slower code. I don't recommend using them.

You could switch to a table lookup, but that's longer code.

if a == 0 and ({[1] = true, [3] = true, [5] = true})[b] then ...

You could define a helper function, but that's also longer code.

local function has_value(tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        end
    end

    return false
end

if a == 0 and has_value({1, 3, 5}, b) then

Again, your code is fine. I would leave it as-is.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-03-04 12:47:22 +0000

Seen: 57 times

Last updated: Apr 02