lua-users home
lua-l archive

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

Hi all,

Lua newbie here.  I'm going through PiL 2nd ed right now as I migrate more and more of our ui system out of c++ and into Lua.  (Maybe I should have read the book *first* :))

Reading the chapter on OO, I'm struck by this

SpecialAccount = Account:new()

I'm guessing that if you had any references as members/fields of the superclass/table that any instance/table that uses it as a metatable will share those members/fields instead of getting their own copy.

So I'm wondering if this is acceptable instead.  It seems to work:

function SpecialAccount:new(o)
  o = Account:new(o)
  setmetatable(o, self) -- blows out the methods of Account
  self.__index = self
  setmetatable(self.__index, { __index=Account}) -- puts them back, leaving those for SpecialAccount
  return o

Is this better than writing a dispatch function for the metatable's __index?  Am I completely misunderstanding something?  I'm getting the impression from the book and from lurking on the list that there's no such thing as idiomatic Lua, but I'm still wary of shooting myself in the foot here.