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

0 Members and 1 Guest are viewing this topic.

Offline aeTIos

  • Nonbinary computing specialist
  • LV12 Extreme Poster (Next: 5000)
  • ************
  • Posts: 3915
  • Rating: +184/-32
    • View Profile
    • wank.party
[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:

Offline Jim Bauwens

  • Lua! Nspire! Linux!
  • Editor
  • LV10 31337 u53r (Next: 2000)
  • **********
  • Posts: 1881
  • Rating: +206/-7
  • Linux!
    • View Profile
    • nothing...
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 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 :)

Offline Adriweb

  • Editor
  • LV10 31337 u53r (Next: 2000)
  • **********
  • Posts: 1708
  • Rating: +229/-17
    • View Profile
    • TI-Planet.org
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
TI-Planet.org co-admin.
TI-Nspire Lua programming : Tutorials  |  API Documentation