Trying to understand this lua snippet -


i trying understand function does. can explain me?

function newinstance (class)     local o = {}     setmetatable (o, class)     class.__index = class     return o end 

it called this:

self = newinstance (self) 

this function apparently serves provide variant of oop in lua (a bit sloppy in opinion).

this factory class.

it may rewritten follows, clarity:

c = { }  c.foo = function(self) -- method, class not empty   print("foo method called", tostring(self)) end  c.__index = c -- (a)  function newinstance(class)   return setmetatable({ }, class) -- (b) end 

now if create 2 new instances of c, see both have method foo(), different self:

o1 = newinstance(c) o1:foo() --> foo method called  table: 0x7fb3ea408ce0  o2 = newinstance(c) o2:foo() --> foo method called  table: 0x7fb3ea4072f0 

the foo methods same:

print(o1.foo, o2.foo, o1.foo == o2.foo , "equal" or "different") --> function: 0x7fb3ea410760    function: 0x7fb3ea410760    equal 

this because table c (the "class") __index ((a) above) of metatable of o1 , o2, set in (b). o1 , o2 2 different tables, created @ (b) (the "class instances" or "objects").

note: set c.__index equal c @ (a) reuse 1 table. following has same effect:

prototype = { }  prototype.foo = function(self) -- method, class not empty   print("foo method called", tostring(self)) end  c = { __index = prototype }  function newinstance(class)   return setmetatable({ }, class) end  o = newinstance(c) 

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -