lua-users home
lua-l archive

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



El 27/01/2005, a las 11:29, Michael T. Richter escribió:


I love Lua, I want to continue using Lua, but the only reason I'm discussing OOP in Lua is the lack of an alternative.
[...]
Have you looked at Io?

Io is a very interesting language, but it is, at this point, militantly gcc+bash+a-whole-bunch-of-UNIXisms-dependent.

Io seems interesting to me as well, and regarding OOP I think that the prototypical approach of Io to OOP can be useful in Lua as well. I feel quite comfortable without having classes at all, especially in a scripting language like Lua. So my principal ideas in this picky topic are, as with the rest of Lua, «keep it simple» and «small is beautiful». So I sometimes use code like the following in scripts:

------------ 8< -------------------cut here---------------

-- Clones an object ("self"), using the "additions" table as the -- object itself setting its metatable to index "self" so the
-- inheritance chain is created.
clone = function (self, additions)
  additions = additions or {}
  if (type(self)=="table") then
    setmetatable(additions, { __index = self })
  end
  return additions
end

-- Obtains the prototype of an object ("self").
proto = function (self)
  return rawget(getmetatable(self), "__index")
end

-- Now we can (easily) create the "root" object prototype.
Object = { clone = clone, proto = proto }

-- ...and create new objects
List = Object:clone {
  add = function (self, list)
    for i = 1, list:count() do
      self:append(list[i])
    end
    return self
  end,
  append = table.insert,
  count  = table.getn
}

-- Let's fiddle a bit with a list
l = List:clone { "a", "b", "c" }
l:append("d")
l:append("e")
print(l:count(), l[3])

------------ >8 -------------------cut here---------------

Due to the dynamic properties of the Lua language I think hiding attributes might not be the better approach. One can make use of a car to go from here to there, or to running over someone. I prefer the «if I don't know nothing about it, better I'll leave it untouched». Note that I don't use multiple inheritance... usually it's not needed at all, and when you want to do something similar, you can double-clone:

List = Object:clone {
  -- some code here
}

Stack = Object:clone {
  -- some more code here
}

StackList = List:clone(Stack) -- Magic beans!

--
Adrian Perez
GPUL/CLUG member » http://gpul.org
Keyboard Error: Press F1 to resume.

Attachment: PGP.sig
Description: Mensaje firmado digitalmente