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

Attempt to create a Class but it doesn't seem to work. Could someone help/explain, please?

I don't really want to create anything in specific. I'm simply messing around with scripting and trying out new techniques. An interesting one is the use of metatables for classes. Using things such as self and other cool things to make the code useful...

First, here is what I have so far. The model hierarchy is as follows: Part, Part\Script and Part\Script\ModuleScript

The script has the following code:

local module = require(script:WaitForChild("ModuleScript"))
local newClass = module.new(script.Parent) -- this would be the brick

newClass:changeColor(BrickColor.new("Really black"))

And the ModuleScript has this code:

local module = {}
module.__index = module -- setting a metamethod

function module.new(brick)
	assert(brick:IsA("BasePart"), "parameter must be set to a basepart")
	local class = setmetatable({
		part = brick;
	}, module)
	
	return class
end

function module:changeColor(color)
	self.BrickColor = color
end

return module

What I would like it to do is change the color of the brick.. however, I don't think I really understand how this works as nothing happens.

Furthermore, the output doesn't tell me anything so I really can't be sure.

I hope you understand what I'm trying to do and any help towards achieving this would be appreciated.

Yours faithfully, Rod455

1 comment

0

worth noting I have never done this before and am merely testing... can't seem to fix it though

1 answer

✓ Accepted answer

self points to the object it is being called on.

self is not pointing to the part as you think it is. The implicit self parameter is pointing to newClass.

The solution is to index for self.part and change the BrickColor of that.

If you want to not do that, and just be able to use self directly, you can use another metamethod, specifically, __newindex. It is invoked when a new index is added to a table.

module.__newindex = function(self, property, new)
	self.part[property] = new
	rawset(self, property, nil)
end

Since __newindex won't be invoked again if the index already exists, I set it to nil via rawset, since it does not invoke __newindex.

Debugging is important

Always debug what you think is not working. When you said it was not working, it was ambiguous: is it not running? Is it doing something other than what you want? You have to be specific.

print calls are often used in debugging to test that the code is actually running, only that their program does what is not desired

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