How to detect when a table is accessed?

How would I detect when a table is accessed, even if the value is not nil?

Ex:

local x = {[“Player”] = mem}

x[“Player”] – Accessing here

This would be rather straightforward using metatables if I were wanting to access it when the value was nil, but in this case I want a function to be called when any element of the table is accessed.

1 Like

I’m unaware of any special way to do this but I would assume most people would just write a function to access this part of the table, return what the value is, etc but I don’t think this is the answer you are looking for.

function module:AccessValue(v)
return x[v]
end

I would recommend using RunService / heartbeat to detect a change in a table if you do not want to use __index w/metatables. I don’t know why anyone would want to do it this way though.

You could do something like this

local x = {
	Player = "bob"
}

local newTable = setmetatable({}, {
	__index = function(self, i)
		print("Indexing", i)
		return rawget(x, i)
	end
})

print(newTable.Player)

print(newTable.test)

image

1 Like