Page 1 of 1

Find if an item exists in an array

Posted: Sun Jan 17, 2010 11:51 pm
by juraj
I'm having trouble finding an appropriate function for what I want to do. I'm used to using the existence of an item in an array to track things in other clients, and I was hoping that there was a function to do the same in Lua. I'm looking for something that will return 1 or true if a string exists inside a given array, and 0, false, or nil if it doesn't.

Example:
>> foo = {"one fish", "two fish", "red fish", "blue fish"}
>> function_I_want_to_use( foo, "one fish")
true
>> function_I_want_to_use( foo, "lorax")
false

something along those lines

Re: Find if an item exists in an array

Posted: Mon Jan 18, 2010 1:22 pm
by davidk
The fastest way would be to use your item names as keys, e.g.
foo = { ["one fish"] = true, ["two fish"] = true, ...}
Then you can test for the existence using the expression foo["one fish"].
If for some reason you cannot have such a lookup table you would have to use the pairs function to iterate through the whole table.