Detecting when a dictionary is changed

So basically I need a way to detect if a dictionary is changed that way I can scan its contents and see if they are all a certain representation. I’ve heard stuff with metatables but I have a very high level understanding of how they work as well with userdatas but not really enough to understand how to code with them. Maybe i’m just overlooking something and theres a more easier way so just feel free to tell me

Something like this should work

local dictionary = {
  foo = "bar"
}

local newDictionary = setmetatable({}, {
    __newindex = function(t, k, v)
        if dictionary[k] then
            print("changed")
        else
            print("new key")
        end
        dictionary[k] = v
    end,
    __index = dictionary
})

newDictionary.foo = "bar1"
newDictionary.foo = "bar2"
newDictionary.foo = "bar3"

Since the __newindex metamethod is called when a new key is added, you have to use a second table which doesn’t get anything added to it, it acts like a proxy.

6 Likes

I’ve already found an alternative for my game (its just a while wait(1) do thing) but I tried doing what you did in the lua demo and it seemed to not work (after changing the table from a array to a dictionary)

Lua

local dictionary = {
  [foo] = "bar"
}

local newDictionary = setmetatable({}, {
    __newindex = function(t, k, v)
        if dictionary[k] then
            print("changed")
        else
            print("new key")
        end
        dictionary[k] = v
    end,
    __index = dictionary
})

newDictionary["foo"] = "bar1"

Is this something on my end or does the lua demo compiler just work differently than the roblox version?

local dictionary = {
  [foo] = "bar"
}

Since it’s in [], it will try finding for a variable called foo, which is nil. I think you wanted to do

local dictionary = {
  ["foo"] = "bar"
}

See that’s the problem. In my code it is structured as a dictionary and not an array causing that issue. Is there a way I could change the code you posted so it will work with dictionaries?

**edit misread

1 Like

By any chance could you explain how the code works? I have no idea what im looking at is why :grin:

1 Like

Basically, it creates a new table called newDictionary which has metamethods: __newindex and __index. The __newindex metamethod is called when you want to add a key to the table. Since a key never gets added to newDictionary, the __newindex metamethod will still be called while the key is being added to the original dictionary.

The __index metamethod is called when the table index is nil. Since it’s always nil, it will look in the original dictionary table to find the value.

sorry, i can’t explain very well :sweat_smile: