Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need to the same thing for 4 conditions else do something else

I have VERY recently had to learn LUA. I have system that I need translate to LUA. The code is to read an XML file.

cat = elementAttributeTable["Category"] -- This will be 3 char code.

Now, if cat is, i.e. "MUS" or "MUA" or "XMS", I need to process other elementAttributeTable[] information. Else do some default stuff.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have seen some info using a Table, but can’t find an if in_table() thing.
Other languages have the Select…Cas, that I don’t see in LUA.

Can somebody help me with this? Thanks in advanced.

>Solution :

One straightforward way to express this is using or:

if cat == "MUS" or cat == "MUA" or cat == "XMS" then
    -- process information
else
    -- default behavior
end

given the few values you are testing for, this is completely fine.

You might want to write yourself a helper:

local function equals_any(value, ...)
    local n = select("#", ...)
    for i = 1, n do
        if value == select(i, ...) then
            return true
        end
    end
    return false
end

Usage: if equals_any(cat, "MUS", "MUA", "XMS") then ... end.

Alternatively, if you want a more "data-driven" approach or have many more categories to check for (such that it negatively affects performance), you could use a table:

local categories = {MUS = true, MUA = true, XMS = true}
if categories[cat] then
    -- process information
else
    -- default behavior
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading