G
G
Gigabait2016-02-24 07:04:53
Lua
Gigabait, 2016-02-24 07:04:53

How does the self variable work?

Could you explain how it works in a better way? I read 6 sites about lua where there was a self variable, but did not understand.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Lerg, 2016-02-24
@Lerg

Lua is by design a very simple language. And self is the most ordinary variable, its peculiarity is that it is automatically created when using a colon in the declaration or calling functions (which are inside the table). And so self is the link to this table.
You can take this example:

local cat = {}
cat.name = 'Fluffy'
function cat:sayName()
  print(self.name)
end

cat:sayName()

We create the cat table, make the name string field, declare another function separated by a colon, and it becomes possible to use self.
Next, here is an example of absolutely identical code, I’ll just remove all the syntactic sugar:
local cat = {}
cat['name'] = 'Fluffy'
cat['sayName'] = function(self)
  print(self['name'])
end

cat:sayName()

Or so
local cat = {}
cat.name = 'Fluffy'
cat.sayName = function(self)
  print(self.name)
end

cat:sayName()

Or so
local cat = {
  name = 'Fluffy',
  sayName = function(pet) -- не обязательно self
    print(pet.name)
  end
}

cat:sayName()

Or even so
local cat
local name = 'Fluffy'
local sayName = function() -- вообще пусто
  print(cat.name)
end

cat = {}
cat['name'] = name
cat['sayName'] = sayName

cat:sayName() -- Или просто cat.sayName() через точку

S
Sergey Krasnodemsky, 2016-02-24
@Prognosticator

By analogy with other languages, this.
Read Chapter 16 "Object-Oriented Programming" in the book "Lua Programming" by Robert Yeruzalimsky (roottracker at your service).
Here is https://www.youtube.com/watch?v=F-xJq6s6lK0 video explaining the work of self (eng).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question