lua-users home
lua-l archive

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

On Thu, Aug 21, 2008 at 2:02 PM, Mark Meijer <> wrote:
> Eric's solution is a bit different because it doesn't use local
> functions (don't know why).

There's no need for the locals. You can just store the functions in
your table directly. In other words, rather than doing this:

   local a = function(self) end
   local b = function(self) end
   local z = function(self) end
   local prototype = {
      a = a,
      b = b,
      z = z,

You can just do this thi:

   local prototype = {
      a = function(self) end,
      b = function(self) end,
      z = function(self) end,

Or, if you don't want to declare your functions in the table
constructor (matter of taste), you can achieve the same result:

   local prototype = {}
   prototype.a = function(self) end,
   prototype.b = function(self) end,
   prototype.z = function(self) end,

Which is exactly equivalent to (via syntax sugar):

   local prototype = {}
   function prototype:a() end,
   function prototype:b() end,
   function prototype:z() end,

I just find the latter most readable.

> this is equivalent to Eric Tetz's solution, I believe. Except
> without the shallow copying (why was that in there?)

If you have your methods in a table, you can copy them to the new
object in a loop. I could have written the factory like this:

     factory = function()
        local new = {}
        for k,v in pairs(prototype) new[k] = v end
        return new

But the body of 'factory' is a commonly used routine (shallow copy of
a table) that most Lua programmers already have it their library. I
just happen to call mine 'clone'. I just assumed you would use such a
function rather than repeating that same loop in every factory:

     factory = function()
        return clone(prototype)

By the way, my first post has a screwed up version of 'clone' (I was
just typing off the top of my head). I forgot to actually return the
table. :)

Anyway, Mark Meijer's method is the way more people do it. I just
wanted to show Alexander that creating a bunch of locals before
assigning them to table fields is unnecessary; you can just assign
them to table fields to begin with.