#Best way to check if a variable is one of several options in Lua

11 messages · Page 1 of 1 (latest)

crimson glacier
#

I know three ways to do this.

  1. Multiple or in a single statement
if (variable == "a") or (variable == "b") or ... then
  code
  1. Define a table and iterate over it with ipairs:
x = {"a", "b"...}
for i, var in ipairs(x) do
  if variable == var then
    code
  1. Define a table with the possible values as keys instead
x = {["a"] = true, ["b"] = true...}
if x[variable] then
  code

I have been using 3 since it seemed like the most efficient in terms of execution, but writing every key as true seems so cumbersome. Surely there's a more elegant way to do something this simple?

languid bluff
#
  1. write a table like in 2 and then use a function to check it
crimson glacier
#

seems like it would save one layer of indentation at the cost of more lines separately, or I guess that function could be reused if there are multiple tables

#

the process of checking if something is in a list by iterating over a table is slower than checking the key (as in 3) right?

weak wadi
#

I've just been using 3 all this time

languid bluff
languid bluff
crimson glacier
#

where would you go to learn about things like how efficient different methods and functions are

languid bluff
# crimson glacier where would you go to learn about things like how efficient different methods an...

you'd run 500,000 tests and note the average time taken and compare the two, there's really no other way. in theory a hashtable would be faster since it's constant time, but in practice A) you have to compute the hash and B) memory access isn't exactly constant time. meanwhile an array gets all stored together so it probably fits nicely in cache and you only need to add 1 to the pointer each time. However Lua is a dynamic language so that might not apply

Basically, unless you're running the function 100,000 times it doesn't matter, just use whatever's easier