#What is self

11 messages · Page 1 of 1 (latest)

sturdy ruin
#

What is self and why is it red

high ginkgo
noble jolt
#

its by default when you do methods to an object

#
local object = {name = "foo"}

function object:Hello()
  print(self.name) -- self here is the object
end

object:Hello()
abstract boughBOT
#
Program Output
foo

noble jolt
#

but its just a variable name so you can clearly do

local self = 3
print(self)
abstract boughBOT
#
Program Output
3

thick ravine
# sturdy ruin What is self and why is it red

self is an automatic parameter assigned to a function with : which always refers to the object that the function was called, and it 99% of the time is a table as the person above me showed. A function is assigned as a key of the object:

object:Hello = function()

And self is automatically assigned as the first parameter for the : method, so the function above is the same as
object.Hello = function(self)

So self is the same as object. Usually made to work with Object Oriented Programming.