Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can you find if a certain value is in a table? [ANSWERED]

Asked by
Kyokamii 133
7 years ago
Edited 7 years ago

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!

2 answers

Log in to vote
0
Answered by 7 years ago

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
0
Hello, I found a solution and you posted the answer! I'll take note and Accept your answer :) Kyokamii 133 — 7y
Ad
Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

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

Answer this question