Find if an item exists in an array

Post Reply
juraj
Posts: 15
Joined: Wed Jan 13, 2010 2:47 pm

Find if an item exists in an array

Post 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

davidk
Posts: 13
Joined: Wed Dec 09, 2009 7:01 pm
Location: avalon.mud.de

Re: Find if an item exists in an array

Post 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.

Post Reply