Is this good use of metatables?

Here’s my code:

--server script
local metatbel = {
	__newindex = function(Table, index, value)
		local plr = {}
		
		plr.Object = value
		
		plr.kill = function(self)
			self.Object.Humanoid.Health = 0
		end
		
		rawset(Table, index, plr)
	end
} 

local PlayerArray = {}

setmetatable(PlayerArray, metatbel)

PlayerArray["alexfinger21"] = workspace:WaitForChild("alexfinger21")

PlayerArray["alexfinger21"]:kill()

I am trying to find use of metatables, is this how I properly use them?

1 Like

Pretty sure they are effective if placed in a module scripts, so other scripts can require it.

Creating the kill function inside the __newindex defeats the purpose of having a self argument. You should either create the function outside and assign it in the metamethod, or remove the self parameter and use . syntax for calling the function.

6 Likes

Metatables are perfectly fine to use in scripts that are not modules?

You don’t necessarily need to use metatables for the module to be required. I don’t think im getting your point. All metatables do is give extra power to tables.

3 Likes

I know, I was just practicing : functions too, since I rarely use them. Just wanted to see how to use them properly.

Just wanted to comment that : functions works regardless if it has a metatable or not, all it does is pass the table the function was called with as self, and lua will automatically assign it for you when called with the colon operator.

1 Like

Thank you so much! I didn’t know that