I'm practicing OOP and metatables but the following code won't work. I just want to test making a part change color using 'self' instead of directly referencing the object itself.
local s = {} s.__index = s function s.new() return setmetatable({workspace.Part}, s) end function s:colorPart() self.BrickColor = BrickColor.Random() end local newTab = s.new() newTab:colorPart()
Before we get into this it is important that you understand you will learn to utilize OOP better if you work on writing classes and constructors that will actually be beneficial to you.
The following code will accomplish what you are trying to do.
Script, inside SSS:
local PartClass = require(game.ReplicatedStorage.ModuleScript) local MyObject = PartClass.new(workspace.Part) MyObject:ChangeColor(255,255,255)
ModuleScript, inside ReplicatedStorage:
local Class = {} Class.__index = Class function Class.new(trueObject) local thisObject = {} setmetatable(thisObject, Class) thisObject.me = trueObject return thisObject end function Class:ChangeColor(r,g,b) self.me.Color = Color3.fromRGB(r,g,b) end return Class
The reason your code isn't working is because you aren't setting up your constructor very well. When creating objects of a custom class, it is important to make sure everything is set up well. For instance, as you can see above. I give my object the property "me", which represents whatever is passed as trueObject; which should be a part.
The following DevForum article does a pretty good job of explaining OOP in the context of writing custom classes and how to organize it: https://devforum.roblox.com/t/all-about-object-oriented-programming/8585