Programming in lua, objects

Code example:

function Account:new (o)
  o = o or {}   -- create object if user does not provide one
  setmetatable(o, self)
  self.__index = self
  return o
end

taken from:

http://www.lua.org/pil/16.1.html

What is the goal:

self.__index = self

line? And why is it executed every time an object is created?

+5
source share
5 answers

As others have said, self(table Account) is used as a metatet assigned to objects created with new. Simplifying a bit (more detailed information is available via links), when a field is not found in 'o', it goes to the Account table, because o metatable says to go to Account (this is what it does __index).

However, it should not be executed every time an object is created. You could just as easily paste this somewhere:

Account.__index = Account

and that will work too.

, o , __index, o __index (__index ). o , __index . , , .

+5

Lua , Lua, .

self._index = self , o; Account.

_index ; self._index - Account. , Account metatable o, _index "" o. (, Account o.)

...

(1)    setmetatable(o, self)
(2)    self._index = self

... Account o (1) _index o Account (2). ( (2) " " __index Account Account.) , self._index = self _index Account, _index o.

:

    setmetatable(o, self)
    getmetatable(o)._index = self
+4

Lua - , - . , a la JavaScript. -, .

__index , . , self.__index = self Account "" ", o = o or {} setmetatable(o, self).

. :

+3

( y = []), . o , self, -. , , , , __index .

0

( ) Lua. , ( ), . CAT .

, Lua , Lua, . , Lua CAT . . , .

CAT, . Self. () : tableName:methodName(), Lua . . , CAT, self .

, CAT Car.

metaCar = { __index = Car }  
-- this table will be used as the metatable for all instances of Car  
-- Lua will look in Car for attributes it can't find in the instance

:

-- instance table is called mustang    
-- setmetatable(mustang, metaCar)

Here is a general purpose function that creates new instance objects and sets a metatet for it. If CAT has a constructor function (init), it will also be executed.

function newObj(metatable)  
..obj = {}      -- create new empty instance object  
..setmetatable(obj, metatable) –- connect the metatable to it  
..if obj.init then  -- if the CAT has an init method, execute it  
....obj:init()  
..end  
..return obj  
end
0
source

All Articles