I have a 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 e.g. "MUS" or "MUA" or "XMS", I need to process other elementAttributeTable[]
information. Else do some default stuff.
I have seen some info using a Table, but can't find an if in_table()
thing.
Other languages have the Select...Case
, that I don't see in Lua.
How could I do this?
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