`self` is always returning the exact same table

Did you print the table or run the functions?

2 Likes

newObj is being returned

function object.new(parent, position: Vector3)
	test += 1

	local newObj = setmetatable({}, object)
	newObj.test = test

	-- create the model for this object
	local visual = visuals.coin.new()
	newObj.visual = visual

	if position then
		visual:move(position)
	end
	--
	print(tostring(newObj))
	return newObj
end
1 Like

Did you run the functions? Because when you run them, they should work.
The functions will not appear inside the newObj table because they’re not set inside the newObj table, but rather in the object table.

Due to this, when you index newObj with the move key like newObj:move(), since move isn’t in the newObj table, Luau will run the __index metamethod, which then looks through the object table and sees if object table has the move function, and since in this case, it has it, it will return the move function through it. This is why the newObj table seems empty when you use tostring, but it will run the functions just fine.

2 Likes

This worked, but I do want to note that I did modify the code I tiny amount. I set newObj’s __index to object and I called newObj:move instead of visual:move
This is giving me the result I want!

image
image
Notice how the objects were moved from their initial position (top image)
Thank you so much for your help, I would’ve been stuck here for another 12 hours!!

Here’s the edits incase you’re curious.

function object.new(parent, position: Vector3)
	test += 1

	local newObj = setmetatable({}, object)
	newObj.__index = object
	newObj.test = test

	-- create the model for this object
	local visual = visuals.coin.new()
	newObj.visual = visual

	if position then
		newObj:move(position)
		--visual:move(position)
	end
	--
	print(tostring(newObj))
	return newObj
end
1 Like

I quite don’t get why you did this though, how did this help? newObj should be a normal table.

2 Likes

I wrote this just as an extra safety measure if that makes sense, because while I was working on this yesterday __index seemed to have caused issues. Honestly don’t remember the details in its entirety.

1 Like

That line will absolutely do nothing I’ll assure you. __index is a metamethod that only works in metatables. setmetatable() only returns the given table.

2 Likes

Removed it and I got the same result, thanks for the clarification!

2 Likes

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