Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: aeTIos on May 15, 2012, 06:21:53 am

Title: [Lua] Check if array contains given value
Post by: aeTIos 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 :)
Title: Re: [Lua] Check if array contains given value
Post by: Jim Bauwens 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 false
end

tbl = {"a", "b", 2, 1, 1337}
print(inTable(tbl, "b"))          -- Print's 3 (the position of "2")
print(inTable(tbl, "theGame")) -- False
print(inTable(tbl, 1337))         -- 5

Anyway, what are you using it for? Lua quite some table tricks, so maybe I can offer a better solution :)
Title: Re: [Lua] Check if array contains given value
Post by: Adriweb 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