How do I create a table like the Properties table?

I’m trying to do object oriented programming, but I don’t know how to write the Properties table

Here is an example

local MainModule = {}
MainModule.__index = MainModule

function MainModule.new()
    local PropertiesClass = {}
    setmetatable(PropertiesClass, MainModule)

    PropertiesClass.Health = 0

    OnTableChange(PropertiesClass, function(ValueName, Value)
        print("Change:", ValueName, "=", Value)
    end)

    return PropertiesClass 
end

return MainModule

When Health is changed, print Change: Health = 10

1 Like

You can just use a BindableEvent for this:

MainModule.OnHealthChange = BindableEvent.Event
MainModule.OnHealthChange:Connect(function()
    -- code
end)

But you’ll have to manually fire it:

BindableEvent:Fire()
1 Like

Create a new table called “PropertyClassProxy”.
Create a new table entry inside of the created table called “Changed”.
Create a new table entry inside of the “Changed” table called “Connections.”
Create a function called “Fire” or “FireAllKeys”.
It should look like this.

local PropertyClassProxy= {};
PropertyClassProxy["Changed"] = {};
PropertyClassProxy["Changed"].Connections = {};
function PropertyClassProxy.Changed:FireAllKeys(key, value)
	for i,v in pairs(PropertyClassProxy.Changed.Connections) do
			v(key, value);
	end
end
function PropertyClassProxy.Changed:Connect(fn) 
	PropertyClassProxy.Changed.Connections[#PropertyClassProxy.Changed.Connections+1] = fn;
end


Next, set the __newindex of “PropertyClassProxy” to fire all keys when receiving a new entry, and to rawset the index of the original table.
It should look something like this.

setmetatable(PropertyClassProxy, {
	__newindex = function(t,k,v) 
		t.Changed:FireAllKeys(k, v);
		rawset(PropertyClass, k, v)
		rawset(t, k, nil);
	end
})

Then, to use it, all you’d have to do is use

PropertyClassProxy.Changed:Connect(function(key, value)
 print(key, value)
end)

just like in roblox instances.

thank you for your help

30 word

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.