Check if child added in table roblox

Right now I already have a script for checking if there is a new child in a table but it uses loops.
Is there any way to make this more efficient?

You can use a metatable to create a event for your table.

local function onChildAdded(child)
    print("New child added: " .. child)
    -- Your code here
end

local abc = {}

local mt = {
    __newindex = function(table, key, value)
        rawset(table, key, value)
        onChildAdded(value)
    end
}

setmetatable(abc, mt)

-- Example of adding a child to the table
abc[1] = "NewChild"

When a new child is added, the onChildAdded function will be called with the new child as an argument.

2 Likes

I would recommend making a wrapper instead because metatables tend to overcomplicate your structure and slow things.

local Foods = {}

-- Callback
local function OnFoodAdded(Type, Status)
	print(Type, Status)
end

-- Interface
local function AddFood(Type, Status)
	Foods[Type] = Status
	OnFoodAdded(Type, Status) -- Load the Callback
end

AddFood("Burger", "Delicious")

This way you can also easily add a RemoveFood and OnFoodRemoved function without worrying about low-level concepts like metamethods.

4 Likes

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