What is self and what does it do in lua?
Asked Answered
M

1

12

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.

Miley answered 23/3, 2022 at 0:3 Comment(1)
See lua.org/pil/16.htmlLeandraleandre
C
23

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++.

Convivial answered 23/3, 2022 at 9:48 Comment(1)
Great answer. I would recommend to OP to actually code a few simple tables and functions like this and see how they work. i.e. sampleRavage

© 2022 - 2024 — McMap. All rights reserved.