✓ Accepted answer
TL;DR: it's for object oriented programming and when you're saying 'self' you're referring to an instance/object created by the script, not the script itself.
I'm not the best at explaining so here's some tutorials on object oriented programming:
ROBLOX Wiki Article
DevForum article
and watch some youtube tutorials as well. they're more focused on explaining what the concept is rather than how to do it on roblox probably.
- Is the keyword 'self' useful?, if so, how and when?
yea. see question 2
- When's it appropriate to use the keyword 'self'?
self is used in object oriented programming (OOP).
in OOP, you have classes and objects. (objects are instances of the class whereas classes are a blueprint of what an object contains).
an example you're probably familiar with is Instance.new()
When you say Instance.new("Part") you're creating a new part object from the Part class. A part has properties such as Part.BrickColor, Part.Transparency, etc. and it also has methods (functions) such as Part:Destroy() or part:Resize()
It even says that part is a CLASS in the api reference link !!
Anyway, a class would look something like this:
(this isn't what the part class looks like it's just an example of OOP in lua)
Part = {}
Part.__index = Part
call this function by saying: myPart = Part.new()
function Part.new(position)
local newPart = {}
setmetatable(newPart, Part)
newPart.Transparency = 0
newPart.Position = position
return newPart
end
function Part:SetTransparency(newTransparency)
self.Transparency = newTransparency
end
In the example above, there's a SetTransparency() function. The function uses the keyword self. If I was to call myPart:SetTransparency(.5) I'd be setting the part myPart's transparency to .5. When we use self, we are referring to the instance (aka myPart) and it's properties/functions, not referring to the script itself.
- Why was the keyword 'self' made for Lua?, and was it just made for Lua? These are my current questions, feel free to show me code examples, I don't mind at all.
Most high level languages like lua have a keyword like self. The keyword varies per language, but usually it's self or this.
3 comments
I recommend reading the lua pil from chapter 16 to 16.2 https://www.lua.org/pil/16.html
it just makes code look better in OOP
will do