Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to tell when a function in a table is called?

I want to tell from a script when a ModuleScript calls its own function within the table returned, except I'm not entirely sure how.

I'm currently trying to add a metatable to the table from the script calling the ModuleScript but it doesn't seem to be saying the table is being indexed at all

	tableFromModuleScript = setmetatable(tableFromModuleScript, {
		__index = function(self, index)
			print(index .. " is being indexed")
			if self[index] == self.FunctionBeingCalled then
				print("Index is the function")
			end
		end
	})

1 answer

#Problem

The reason the metamethod is not being called is because the index metamethod is called only when an access to a nil value is made.

local table = {"foo" , "goo" , "Hi"}
setmetatable(table , {
	__index = function ()
		print("Access to nil value!")
		return nil
	end
})
print(table[3])
--Prints "Hi"
print(table[4])
--Prints "Access to nil value!"
--Prints "Nil" (the metamethod returns nil)

#Solution

If you want to track every access to a table, you will have to create a proxy table. This is basically an empty table with an index metamethod that makes an access to the original table. Because the table is empty, every access to it will trigger the metamethod. We are also using a do statement here to make the original table completely private. In your specific scenario, the proxy and metamethod would be implemented like so:

do
	local originalTable = tableFromModuleScript
	tableFromModuleScript = {} --proxy
	setmetatable(tableFromModuleScript , {
		__index = function (table , index)
			print(index .. " is being indexed")
			if index == "FunctionBeingCalled" then
				print(Index.. " is the function")
			end
			return originalTable[index]
		end
	})
end

This discussion is preserved as it was. New answers, comments, and votes are closed.