How to use self?

So I don’t really know why use self instead of using local. It only works on functions but I wanna see what it dose. Last time I checked,

local item = {}

function item:test()
	self.hi = "hey"
	local other = "hey"
	print(self.hi, other)
end

It dose the same thing

> hey hey

1 Like

Assuming I have understood your post correctly, self is a Lua variable that is automatically assigned to when doing OOP related programming.

In Lua there are two ways to call a method.

someObject.Method()

and

someObject:Method()

These lines of code will both call the same method, however they’ll do something slightly different with the arguments.

local someObject = {
  Method = print
}

someObject.Method("Test") --> "Test"
someObject:Method("Test") --> table: 0x0000, "Test"

The reason you get table: 0x000 is because the object on which you call the method is passed as an argument automatically when using the : operator.

Now, where does the self variable fit into all of this? Well, you can also define a function using the same syntax as I have shown you above.

function someObject.Method(a, b)
  -- self does not exist here
end

and

function someObject:Method(a, b)
  -- self exists here
end

The difference is that the second example will also have the self variable defined and it’ll be set to the first value passed to the method.

For example

function someObject:Method()
  print(self)
end
someObject.Method("Test") --> "Test"

tl;dr the following two Lua snippets will do exactly the same thing.

function someObject.Method(self)
  print(self)
end

function someObject:Method()
  print(self) -- self is automatically defined
end
5 Likes

Ohh, so the first value passed?

2 Likes

When creating the functions:
function abc:Test() == function abc.Test(self)

When calling the functions:
abc:Test() == abc.Test(abc)

It’s just syntactic sugar. You could even mix those in-between each other and it would still work fine. The most important thing to know is that when you define a function with :, it injects a self argument as the first argument implicitly. And when you call a function with :, it also injects itself (the table it’s attached to) as self for the first argument.

1 Like

self is the table itself, normally passed as the first argument.

local item = {}
item.foo = "1"

function item:test()
print(self.foo)
end

function item.test2(self)
print(self.foo)
end

print(item:test()) -- 1
print(item:test2()) -- 1
print(item.test2()) -- attempt to index nil with foo