lua-users home
lua-l archive

About the example in "Object-Oriented Programming" on http://www.lua.org/pil/16.1.html

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


hi

I am a freshman in lua programming,and I worked with _javascript_ for several years

when I write a simple game framework using lua , I read the article on on

http://www.lua.org/pil/16.1.html,the thoughts much like the prototype,but I noticed a code fragment

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

I think "self.__index = self" is not make sense,it will lead to a "prototype circle",
because when you call Account:new({}) after, the table Account will have a 
prototype point to himself,and if you dump Account (loop each key in it,if is a table,loo
p the table and so on,in recursive),you will get an stack overflow error..... And in logic
when you create a "instance" of a "Class",you shouldn't change the "Class's" property or behavior 
I think it should code like this
 function Account:new (o)
 o = o or {} -- create object if user does not provide one
 setmetatable(o, {__index = self})
 return o
 end
It's much easy to understand,and when you create instance of Account,you will not change the

Account's any definition,and the table o(instance) also have a prototype point to Account(Class),it can call the method of the Account(Class)。

And I wrote a lua version simple-inheritance like JR's _javascript_ version

https://github.com/dafong/Lua-Simple-Inheritance

best regards!

AltStyle によって変換されたページ (->オリジナル) /