Why doesn't this print?

local DataMetatable = {}

function DataMetatable.new(name, save)
    if type(name) ~= "string" then return end
    local self = setmetatable({}, DataMetatable)
    self.Name = name
    for _type, value in pairs(save) do
        self[_type] = value
        if _type == "leaderstats" then
            setmetatable(save[_type], {
                __newindex = function(_table, key, value)
                    rawset(_table, key, value)
                    print(key, value)
                end
            })
        end
    end
    return self
end

local DatastoreController = {}

function DatastoreController:Initialize(Player)
    local save
    pcall(function()
        save = DataStore:GetAsync(tostring(Player.userId).."SAVE")
    end)
    save = save or DefaultSave
    
    local _playerData = {}
    for _type, data in pairs(save) do
        if _type == "leaderstats" then
            local folder = DatastoreToFolder(save[_type] or {})
            folder.Name = "leaderstats"
            folder.Parent = Player
        end
        _playerData[_type] = data
    end
    PlayerData[Player.Name] = DataMetatable.new(Player.Name, _playerData)
    PlayerData[Player.Name]["leaderstats"]["Coins"] = 2
end

why doesn’t this print(key, value)

1 Like

Try printing key by itself and tell me how that goes. (Also hi, friend.)

I think you meant to type instead of if _type == "leaderstats" then try if _type.Name == "leaderstats" then.

Because rawset does not trigger the __index and __newindex metamethods, so the __newindex never fires and nothing prints, as expected.

Edit:

They both are not the same, the metamethods were set on the other copy of the table.

no, _type is a string and also, when I do this it prints

function DataMetatable.new(name, save)
	if type(name) ~= "string" then return end
	local self = setmetatable({}, DataMetatable)
	self.Name = name
	print(self.Name)
	for _type, value in pairs(save) do
		self[_type] = value
		if _type == "leaderstats" then
			setmetatable(save[_type], {
				__newindex = function(_table, key, value)
					rawset(_table, key, value)
					print(key, value)
				end
			})
		end
		self[_type]["test"] = 2
	end
	return self
end

but not when I call it out of the function DataMetatable.new

no the metatable is being set to

save[_type]   --aka (save["leaderstats"]) 

which is

PlayerData[Player.Name]["leaderstats"]

but

PlayerData[Player.Name]["leaderstats"]["Coins"] = 2

is not triggering __newindex

but

save[_type]["Coins"] = 2

does trigger it