Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is self and what does it do in lua?

Tags:

self

lua

I'm a new programmer in lua, and there are lots of things I still probably don't know about. I googled what self is in lua, but I still don't understand it. If anyone could give me the easiest explanation for what "self" does in lua, it would be really helpful.

like image 413
guii233 Avatar asked Jan 22 '26 17:01

guii233


1 Answers

self is just a variable name. It is usually automatically defined by Lua if you use a special syntax.

function tbl:func(a) end

is syntactic sugar for

function tbl.func(self, a) end

That means Lua will automatically create a first parameter named self.

This is used together with a special function call:

tbl:func(a)

which is syntactic sugar for

tbl.func(tbl, a)

That way self usually refers to the table. This is helpful when you do OOP in Lua and need to refer to the object from inside your method.

Similar to this in C++.

like image 85
Piglet Avatar answered Jan 25 '26 15:01

Piglet