lua-users home
lua-l archive

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


On Thu, Apr 14, 2011 at 2:54 PM, Michael Gogins
<michael.gogins@gmail.com> wrote:
> There are open, tick, and close functions that derived classes override.
> Inheritance and virtual methods in C++ are a very natural solution to this
> problem.

if those methods are all overridden, then there's no need for the
superclass.  just specify that the objects have to comply with those
requirements.  in most static languages inheritance is the only way
for the compiler to know that all the 'open' functions are supposed to
be interchangeable; but dynamic languages don't care :-)

if the superclass does implement some base functionality, then it's
nice to define subclasses in terms of a prototype; but that only saves
a couple of lines in the class definition:

-- explicit
local derived_mt={__index= {
    open = super.open,
    tick = super.tick,
    close = super.close,
    work = function(...) ... end,
    chat = function(...)...end,
    sleep = function(...)...end,
  }}
function derived_constructor(o, ...)
  o = setmetatable(o or {}, derived_mt)
  -- set some fields of 'o'...
end

vs.

-- with an 'inheritance system'
derived_mt = class(super, {
  work = function(...) ... end,
  chat = function(...)...end,
  sleep = function(...)...end,
})

function derived_constructor (o, ...)
  o =  setmetatable(o or {}, derived_mt)
  -- set some fields of 'o'...
end


hardly anything to write home about.  and as i usually say, you can
bake your own in a few lines:

local function copytable (dst, src)
  dst = dst or {}
  for k,v in pairs(src) do dst[k] = v end
  return dst
end
function class_mt(super, extra)
  return {__index=copytable(copytable(nil, super.__index), extra)}
end

honestly, i prefer the explicit style for those (very) few cases where
a superclass implementation makes sense.


..... and of course, this is usual Lua stuff, no relation to LuaJIT,
except that now you can use  FFI's cdata as objects and not only
tables or userdata (thanks Mike!)


-- 
Javier