Metatable contents returning nil

I’ve not really delved into metatables before and I seem to be having some trouble with them, I’m trying to incorporate them with ProfileService (that isn’t really relevant here) I’m just trying to get an explanation as to why my test metatable doesn’t seem to contain the variables I set. Module below:

local Test = {}
Test.__index = Test

function Test:new()
	local T = {
		A = 'A',
		B = 'B',
		C = 'C',
	}
	setmetatable(T, Test)
	print('set table')
	return T
end

function Test:TestPrint()
	print(self.B)
end

return Test

Server script below:

local T = require(script.Parent.ModuleScript)
T:new()
T:TestPrint()

Am I doing anything wrong? I’ve tried other methods like setting self instead of doing the table template and it still didn’t work lol

1 Like

^ returns nil when printing self.B

1 Like

You arent retrieving the metatable using the variable, for you to use it.

What do you mean? could you post an example

It seems as though you may be having an A > B problem here (where you don’t know how to do A, so you want to try B if it might work, but it’s not actually the solution to A). What are you trying to do with ProfileService?

In any case, it may be because it needs to be .new(), not :new(). Refer to what Cairo said, they’re right.

You’ll want to do this instead:

local T = require(script.Parent.ModuleScript)
local Object = T:new()
Object:TestPrint()
1 Like

So basically, you are calling the function to create a new metatable, and you are returning the said metatable, in order for you to use the new data, you need a variable to be assigned the data:

local mt = T.new()
-- mt will be given the data that was returned from the function

From there, you are able to use the data from the metatable, which is assigned to variable mt as shown above.

ohhhhhhhhh… that’s actually really simple, looks like I’m stupid

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