First time here? Check out the FAQ!
THIS IS A TEST INSTANCE. Feel free to ask and answer questions, but take care to avoid triggering too many notifications.
0

lua concat "and" and "or" statements

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"

tom_titled's avatar
1
tom_titled
asked 2021-03-04 12:47:22 +0000
edit flag offensive 0 remove flag close merge delete

Comments

add a comment see more comments

1 Answer

0

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.

dd4235's avatar
1
dd4235
answered 2021-04-02 16:33:49 +0000
edit flag offensive 0 remove flag delete link

Comments

add a comment see more comments

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss.

Add Answer