### Author Topic: [Lua] Check if array contains given value  (Read 19398 times)

0 Members and 1 Guest are viewing this topic.

#### aeTIos

• Nonbinary computing specialist
• LV12 Extreme Poster (Next: 5000)
• Posts: 3913
• Rating: +184/-32
##### [Lua] Check if array contains given value
« on: May 15, 2012, 06:21:53 am »
Is there a function in lua for checking if an array contains given value? Else I'll create a function for it but its easier for me to do stuff if there's a built in function. thanks
I'm not a nerd but I pretend:

#### Jim Bauwens

• Lua! Nspire! Linux!
• Editor
• LV10 31337 u53r (Next: 2000)
• Posts: 1881
• Rating: +206/-7
• Linux!
##### Re: [Lua] Check if array contains given value
« Reply #1 on: May 15, 2012, 07:03:35 am »
No, there isn't such a function as far as I know.

But this should do the trick:
Code: [Select]
function inTable(tbl, item)    for key, value in pairs(tbl) do        if value == item then return key end    end    return falseendtbl = {"a", "b", 2, 1, 1337}print(inTable(tbl, "b"))          -- Print's 3 (the position of "2")print(inTable(tbl, "theGame")) -- Falseprint(inTable(tbl, 1337))         -- 5
Anyway, what are you using it for? Lua quite some table tricks, so maybe I can offer a better solution

• Editor
• LV10 31337 u53r (Next: 2000)
• Posts: 1708
• Rating: +229/-17
##### Re: [Lua] Check if array contains given value
« Reply #2 on: May 15, 2012, 07:11:07 am »
just    if myArray[key]  then .... end

example :

myArray = { myFunc = function() return "thegame" end, a = "2", 3 }

myArray.a (or [a]) exists, but not myArray[c] (or .c).

so :  if myArray[c] then blblabala end

which is actually if myArray[c] ~= nil then.

edit : ok to jim, I wanst sure of what was asked
« Last Edit: May 15, 2012, 07:16:50 am by adriweb »
My calculator programs