lua-users home
lua-l archive

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


But It's no need to "set Account as its own prototype", and actually there is a circle when you call Account:new(some table),because the sytax sugar colon,the Account is bind to the first hide parameter of the new  unction,in the new function,"self" point to the reciever of current method, it's Account.......

t={}
t.__index = t
setmetatable(t,t)

and I can't understand why we should set the some table's prototype to it's self



2013/4/23 Pierre-Yves Gérardy <pygy79@gmail.com>
On Tue, Apr 23, 2013 at 4:53 PM, xinlei fan <wormlucky@gmail.com> wrote:
>     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 [...]

No, that code doesn't create a cycle unless you call

    Account:new(Account)

Because it would set Account as its own prototype. Here's the minimal code
to create a prototype loop:

    t={}
    t.__index = t
    setmetatable(t,t)

In the PiL example, self becomes the metatable of the new object, not its own.

-- Pierre-Yves