Help comparing dictionary keys

Title is pretty self explanatory. I want to know if there’s a way I can iterate through all the values stored in one dictionary, and then check if their keys store anything in a second dictionary. So the main question is, is there any way I can set up a function that returns the key (in this case a string), rather than the value attached to it. Any help would be greatly appreciated.

1 Like

If you have the value attatched to it, you can conduct a simple linear search to get it.

local function linearSearch<T>(dict: T, value: any): any?
    for key, val in next, dict, nil do
        if (val == value) then
            return key
        end
    end
end

and then you can compare it with the second dictionary:

local key = linearSearch(dict, value)

if (otherDict[key]) then
    --do stuff, it stores a value in different dictionary
end
3 Likes

If you don’t mind can you run me through the parameters you’re using in the first for loop?

1 Like

specifically the purpose of the next, and nil, and what their position is usually used for since I generally see the table/dictionary being iterated through in place of the next.

1 Like

Nevermind, I checked and it’s just the vanilla notation for an in pairs loop lol, sorry for bothering you.

1 Like

This example seems kinda cursed from a Luau standpoint as it mixes (relatively) new language features (generics & type annotations) with a next loop (old Lua optimization trick). Is there any reason you’re using next here instead of the newer, faster, & more idiomatic generalized iteration?

Here’s a simpler, modern example for comparison:

type YourDict = {
    [string]: any, -- i'm assuming your keys are strings and both tables are the same type; change or remove these type annotations as desired
}

--- returns an array of string keys common between dictionary tables `a` and `b`
local function getCommonKeys(a: YourDict, b: YourDict): { string }
    local commonKeys = {}
    for key, value in a do -- `next` and `pairs` are unnecessary in Luau (generalized iteration)
        local valueInB = b[key]
        if valueInB ~= nil then
            table.insert(commonKeys, key)
        end
    end
    return commonKeys
end
2 Likes

yeah that’s what was tripping me up. I appreciate the clarification.

1 Like

Sorry! Force of habit. It’s just the way I like to code, I’m aware of generalised iteration, don’t worry. It’s also just a slight side note and kind of unrelated, but it means if for whatever reason exploiters want to mess with how my table is iterated over they can’t just change __iter metamethod, they have to go through the whole process of trying to hook the function, etc… etc… I won’t go down that now.

But it’s mainly my practice.
Sorry for confusing you @LuxSaar

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.