I need help with detecting when a table changes

local Table = {
coins = 0,
gems = 0
}

How would i detect when the coins changes?

Here’s a script that should help you:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Coins = Instance.new("NumberValue")
local Gems = Instance.new("NumberValue")
local CurrencyFolder = Instance.new("Folder")

CurrencyFolder.Name = "CurrencyFolder"
CurrencyFolder.Parent = ReplicatedStorage

Coins.Value = 0
Coins.Name = "Coins"
Coins.Parent = ReplicatedStorage:WaitForChild("CurrencyFolder")

Gems.Value = 0
Gems.Name = "Gems"
Gems.Parent = ReplicatedStorage:WaitForChild("CurrencyFolder")

local Table = {
    Coins.Value;
    Gems.Value;
}

Coins.Changed:Connect(function(val)
    print(string.format("The coins value was changed to %s", val))
end)

I have tried this however i am specifcally trying to do it through just a script, I heard about meta tables but just trying to find a simpler way.

metatable's would work, however you cannot detect if a value is changed in them. Above is the simplest way to do it, you can even remove some code if you create the values manually.

One way, without metatables is to define getter/setter functions. The purpose of these functions is to act as wrappers for table accesses & assignments.

local Stats = {
	Coins = 0,
	Gems = 0
}

local function GetStat(StatName)
	return Stats[StatName]
end

local function SetStat(StatName, StatValue)
	Stats[StatName] = StatValue
	return StatName
end

A metatable implementation would require the use of a proxy table, take a look at the following example.

local Stats = {Coins = 0, Gems = 0}
local StatsProxy = {}
setmetatable(StatsProxy, {__newindex = function(Table, Key, Value)
	if not Stats[Key] then return end
	Stats[Key] = Value
	print(Key.." stat changed to "..Value..".")
end})

StatsProxy.Coins = 5
print(Stats.Coins) --5

For further information about ‘proxy’ tables, check out the following resources.
https://www.lua.org/pil/13.4.4.html
https://www.lua.org/pil/13.4.5.html

1 Like