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 4 years ago

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

whats the point of this

01local object = {
02    object = true,
03    print("object2")
04}
05 
06function object:colonmethod(parameter1, parameter2)
07    print(self.object)
08    print(parameter1 .." ".. parameter2)
09end
10 
11object:colonmethod("Hello", "World")

when you can do this

01local object = {
02    object = true,
03    print("object2")
04}
05 
06function object.colonmethod(parameter1, parameter2)
07    print(object.object)
08    print(parameter1 .." ".. parameter2)
09end
10 
11object.colonmethod("Hello", "World")
0
might be a stupid question but you know i just got started on tables and methods proROBLOXkiller5 112 — 4y

1 answer

Log in to vote
1
Answered by
Speedmask 661 Moderation Voter
4 years ago
Edited 4 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:

1local Dude = {}
2Dude.ClassName = "Dude"
3Dude.__index = Dude
4 
5function Dude.new(message)
6    local self = setmetatable({}, Dude)
7    self.Message = message
8    return self
9end

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.

1local speedmask = Dude.new("B)")
2print(Dude.ClassName, speedmask.ClassName)
3-- Dude, Dude
4print(Dude.Message, speedmask.Message)
5-- 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.

01function Dude:Speak()
02    print(self.Message)
03end
04 
05local speedmask = Dude.new("B)")
06local proROBLOXkiller = Dude.new("colons are overrated")
07 
08speedmask:Speak()
09-- B)
10proROBLOXkiller:Speak()
11-- 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.

1function Dude.Speak(person)
2    print(person.Message)
3end
4 
5speedmask.Speak(speedmask)
6-- B)

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

Ad

Answer this question