I am working on a script which checks if a value is in a table, but the method I used does not work at all. I was wondering if there is a way to do this? Note that I have no idea the location of the value in the table. Thank you!
✓ ANSWER ACCEPTED
How can you find if a certain value is in a table? [ANSWERED]
2 answers
✓ Accepted answer
A simple function to do this is:
function IsInTable(tab, value)
for i, v in ipairs(tab) do
if v == value then
return true
end
end
end
For an array you would need to do a loop, for a dictionary you can just check its key.
More information about Iterating over arrays
Array:-
local testable = {1,2,3,4,5,6,7,8,9}
function findValue(table, value)
for I, v in pairs(table) do
if v == value then
return true -- the value is found, a return will break out of the loop
-- alternatively
-- return v
-- return I, v -- for both position and value
end
end
return nil -- this is when the value is not found
end
print(findValue(testable , 3))
-- output true
print(findValue(testable , 0))
-- output nil
For a dictionary:-
local testable = { ["a"] = 1, ["b"] = 2, ["c"] = 3 }
-- if you do know the key
print(testable["a"]))
-- output 1
print(testable["d"]))
-- output nil
-- if the key is not known then a loop is required like before except you would return the key
function findValue(table, value)
for I, v in pairs(table) do
if v == value then
return I -- the I is the key witch can be used to access the value contained
end
end
return nil -- this is when the value is not found
end
Hope this helps
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Hello, I found a solution and you posted the answer! I'll take note and Accept your answer :)