How to detect if a value is in a dictionary?

local dict = {
a = 1,
b = 2,
c = 3
}

how to make it if the input is 1, the output will be true, but if the input is 4, the output is false.

Iterate through it, it’s basic and simple to understand. However, you can always check the same key over and over again…

local function isValueInDictionary(dict, targetValue)
    for _, value in pairs(dict) do
        if value == targetValue then
            return true
        end
    end
end
3 Likes

This is Googleable:

1

1 Like

when the targetValue is 4 then it wouldn’t return anything so im gonna make some improvements to this (for @SGP_PRO) and this could be used in any type of table

local function ValueInTable(Table, TargetValue)
    for Key, Value in pairs(Table) do
        if Value == TargetValue then
            return true
        end
    end
    return false
end

Actually, it is intended. The implication is returning nil by default. Nil and false share the same truth value. Although you might just do it just to keep the typing right, that it returns a boolean.

i guess that you can use table.find(t, element), and it checks if table “t” contains element “element” inside of it
Some code example:

local t = {"a", "b", "c"}

print(table.find(t, "b"))
-- prints 1 that is equal to true

print(table.find(t, "d"))
-- prints 0 that is equal to false
2 Likes

I would recommend this solution as table.find uses C (technically C++) code which runs natively and is as a result faster.

Edit:

For OP’s usecase, they probably want to use it this way:

local valueExists = table.find(t,4) ~= nil

You can also use it directly in if statements

if table.find(t,4) then
    -- Even though table.find returns "d", this is seen as truthy, so the if statement accepts it. If it is nil, this is seen as falsey, so it doesn't accept it
end
3 Likes

Keep in mind table.find() performs a linear search and returns only the first occurrence (if you want to find multiple indexes you’re going to need another solution)

2 Likes

An explanation of truthiness (primarily in Lua) for clarification.