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

whats the point of "self" if you can just reference the same thing in a different way?

Asked by 3 years ago

so i was just playing around with tables and i was like

whats the point of this

local object = {
    object = true,
    print("object2")
}

function object:colonmethod(parameter1, parameter2)
    print(self.object)
    print(parameter1 .." ".. parameter2)
end

object:colonmethod("Hello", "World")

when you can do this

local object = {
    object = true,
    print("object2")
}

function object.colonmethod(parameter1, parameter2)
    print(object.object)
    print(parameter1 .." ".. parameter2)
end

object.colonmethod("Hello", "World")
0
might be a stupid question but you know i just got started on tables and methods proROBLOXkiller5 112 — 3y

1 answer

Log in to vote
1
Answered by
Speedmask 661 Moderation Voter
3 years ago
Edited 3 years ago

well, that's it :)

you don't need it. in your case, that is. colons are used for something called static methods. these are functions that do the exact same thing, but are applied to different objects. consider this:

local Dude = {}
Dude.ClassName = "Dude"
Dude.__index = Dude

function Dude.new(message)
    local self = setmetatable({}, Dude)
    self.Message = message
    return self
end

do you recognize this code structure? if not, it's a whole other concept you can go down called lua objects. I do not think there is time to explain what a metatable is, so I will write assuming you know what that is. if not, it doesn't really matter. I'll show you what magic this does.

local speedmask = Dude.new("B)")
print(Dude.ClassName, speedmask.ClassName)
-- Dude, Dude
print(Dude.Message, speedmask.Message)
-- nil, B)

anything in Dude is now static. that means anything you create with Dude.new() will have the same stuff that Dude has. INCLUDING colon functions. conversely, anything that you added inside of the Dude.new() function is its own values.

now you might see where I'm getting at. consider what I have here.

function Dude:Speak()
    print(self.Message)
end

local speedmask = Dude.new("B)")
local proROBLOXkiller = Dude.new("colons are overrated")

speedmask:Speak()
-- B)
proROBLOXkiller:Speak()
-- colons are overrated

see how they used the exact same function, but said something different. each self is different depending on which object used it. you can only do that using self. note that it's the exact same thing as this.

function Dude.Speak(person)
    print(person.Message)
end

speedmask.Speak(speedmask)
-- B)

but that's just weird to write. the colon makes it look nicer :)

Ad

Answer this question