lua-users home
lua-l archive

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


Thanks for the reply Eduardo. My question was more focused on not using "module" to declare the class as in:

module("lk.Dir", package.seeall)

If we don't clutter the global namespace and declare methods on the library, is there any need for "module" ?

Gaspard

On Sun, Mar 27, 2011 at 4:33 PM, Eduardo Ochs <eduardoochs@gmail.com> wrote:
Hi Gaspard,

On Sat, Mar 26, 2011 at 12:10 PM, Gaspard Bucher <gaspard@teti.ch> wrote:
> Hi list !
> I am wondering if there is anything wrong when defining "classes" in this
> way (without using module):
> ======== file lk.Dir ===============================
> local lib = {sep = '/', ignore_pattern = '^[.]', type='lk.Dir'}
> lib.__index = lib
> lk.Dir = lib
> setmetatable(lib, {
>   -- new method
>  __call = function(table, arg)
>   local instance = {path = arg}
>   setmetatable(instance, lib)
>   return instance
> end})
> -- private
> local function some_helper(self, x, y)
>   -- ...
> end
> -- public
> function lib:glob(pattern)
>   -- ...
> end
> --- etc
> ======== file lk.Dir ===============================

I've been super-happy since about january using something
very similar to your idea:

 Class = {
     type   = "Class",
     __call = function (class, o) return setmetatable(o, class) end,
   }
 setmetatable(Class, Class)

 otype = function (o)  -- works like type, except on my "objects"
     local  mt = getmetatable(o)
     return mt and mt.type or type(o)
   end

Here's a demo:

 Vector = Class {
   type       = "Vector",
   __add      = function (V, W) return Vector {V[1]+W[1], V[2]+W[2]} end,
   __tostring = function (V) return "("..V[1]..","..V[2]..")" end,
   __index    = {
     norm = function (V) return math.sqrt(V[1]^2 + V[2]^2) end,
   },
 }
 v = Vector  {3,  4}  --  v = { 3,  4, __mt = Vector}
 w = Vector {20, 30}  --  w = {20, 30, __mt = Vector}
 print(v)             --> (3,4)
 print(v + w)         --> (23,34)
 print(v:norm())      --> 5
 print( type(v))      --> table
 print(otype(v))      --> Vector
 print( type(""))     --> string
 print(otype(""))     --> string

For more information see:

 http://angg.twu.net/blogme4/eoo.lua.html
 http://angg.twu.net/dednat5/eoo.lua.html

Cheers,
 Eduardo Ochs
 eduardoochs@gmail.com
 http://angg.twu.net/