__newindex metamethod

Hey! So im trying to make a custom event for my leaderstats and currently i have this:

local HiddenStats = {}
local Events = {
  ["Money"] = function()
    print("Money value changed!")
  end
}

HiddenStats.__newindex=function(t, k, v)
  if HiddenStats[k] then HiddenStats[k]() end
  rawset(t, k, v)
end

local template = {
  Money = 0,
  Kills = 0,
  Deaths = 0
}

local NewStat = setmetatable(template, t)

NewStat["Money"] = 20

I was just curious if this is ever recommended (am i being efficient or is this not necessary when commpared to the alternatives)? I want to refrain from using instances and keep as much as I can in code.

An easy alternative to this would to simply use Values (like stringvalue, intvalue, etc…).

Can I get feedback?

I wouldn’t really go this route.

Also note __newindex only fires when a new index was added to the table. Modifying the value of an existing key will not cause the metamethod to invoke again.

I personally like the idea of using a modular approach here with mutators to modify a specified stat by an amount. Doing this gives you increased control. You can fire an event, run additional logic as needed before performing the arithmetic operation, etc.

example of what I mean:

local statLibrary = {}

function statLibrary.UpdateStat(statName, value)
--//apply change to the specified stat
end

2 Likes