Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How does the' self' parameter work in OOP?

Asked by 5 years ago

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()


0
Self, is usually the variableName for the metatable attached to the regular table, much like people tend to use i,v in table loops. You can name it whatever you want Ziffixture 6913 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago

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

0
Thisnis the mlst confusing thing ever Ziffixture 6913 — 5y
0
Thank you so much! This helps a ton! YabaDabaD0O 505 — 5y
Ad

Answer this question