samedi 8 juillet 2017

LUA - Most resource efficient way to compare a variable to a fixed list of values

DISCLAIMER: I'm new to LUA, as in started an hour ago, I know a good deal of Java, Javascript, and Python so if things can be put in relation to any of those, I'm sure it'll help me understand better.

So I have a variable, let's call it 'ID'. I need to check this value relative to a fixed amount of values. The ID, of course, can only match one of the values so there isn't an issue with stopping on the first matching value as none of the others would match. There is also a chance that the variable does not match any of the given values, too. My question is then, what is the most resource efficient way to do this? I can think of two easy ways of tackling the problem. Since I know the values at the time of programming I can setup a conditional with 'or' that just checks each value, like so:

if (ID == "1" or ID == "16" or ID == "58") then
    --do something--
end

The problem with this is that it's quite verbose and tedious to write. The other option involves a foreach loop where I define a table beforehand.

values = {"1", "16", "58"}
for (value in values) do
    if(ID == value) then
        return true
    end
end

The upside to this is it's reusable which is good since I'll need to do this exact check with a different set of values at least 10 times, the downside is I suspect it takes more resources.

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire