Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Checking if variable has changed inside class without loops?

Asked by 7 years ago
Edited 7 years ago

So i have this Player class in module script:

local module = {}

function module.new()
    local obj = {}
    obj.Name = 'Player1'    

    obj.eChanged = Instance.new('BindableEvent')
    obj.Changed = obj.eChanged
    return obj  
end

return module

The problem is i want to detect change in class if i change any property, "Name" for example. Now you would say i could use SetFunctions() , example SetName() and then fire the bindable event inside class but i would like to detect change through metatables instead and let metamethod fire the Bindable Event but i ran into problems, heres example code:

local ScriptService = game:GetService('ServerScriptService')
local Player = require(ScriptService:WaitForChild('Player'))


local player = Player.new()

setmetatable(player,{
__newindex = function(tbl,key,val)
print('Detected change on property and returning property'..key)
tbl.Changed:Fire(key,val)


player.Changed.Event:connect(function(property, val)
    print('Detetected change on property: '..tostring(property)..' '..val)
    --do stuff here
end)


--[[i want to let the metamethod __newindex do the job of detecting if already existing variable exaple Player.Name was changed to for example 'mastermarkus' and then fire Changed event inside player class, but the newindex is only fireing if Player.Name is nil already in Player class, but i need to have default name inside player class and detect change evereytime already existing variable was changed to something else.
 ]]



})

Quick Points 1)If Player.Name is set to something other than nil already in player class and then i change player.Name to some other string the __newindex doesn't fire, why?

2)If Player.Name is set to nil by default in player class and then change the player.Name to string then it fires but only once and doesn't detect new change after that anymore.

Is it even possible to create this detect variable change in class system without loops , or do i have to fire the Change event myself through SetFunctions etc.. everytime i change property?

1 answer

Log in to vote
0
Answered by 7 years ago

Never mind i found solution to my problem by looking at roblox new chat system code

Example code what i was looking for:

local module = {}


local ChangedEvent = Instance.new("BindableEvent")

local proxyTable = setmetatable({},
{
    __index = function(tbl, index)
        return module[index]
    end,
    __newindex = function(tbl, index, value)
        module[index] = value
        ChangedEvent:Fire(index, value)
    end,
})

rawset(proxyTable, "SettingsChanged", ChangedEvent.Event)
Ad

Answer this question