lua-users home
lua-l archive

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


>When defining an object, I follow this idiom:
>
>local factory
>do
>  local method1 = function(self)
>    print("method1", tostring(self))
>  end
>
>  local method2 = function(self)
>    print("method2", tostring(self))
>  end
>
>  local methodN = function(self)
>    print("methodN", tostring(self))
>  end
>
>  factory = function()
>    return
>    {
>      method1 = method1;
>      method2 = method2;
>      --...
>      methodN = methodN;
>    }
>  end
>end
>

Is there any particular reason you're doing it in this form? At least with your simplistic example, I don't see any real benefit to this over

local factory;
do
   local mt = {};  
 
   function mt:method1()
      print("method1", tostring(self));
   end
  
   function mt:method2()
      print("method2", tostring(self));
   end

   -- etc etc, to methodN

   factory = function()
      return setmetatable({}, {__index = mt});
   end
end


Which is by far one of the most common uses of metatables.

-- Matthew P. Del Buono