lua-users home
lua-l archive

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


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

2008/8/21 Mark Meijer <meijer78@gmail.com>:
> You could simply move the table construction outside of the factory
> function, to the same scope as the local functions:
>
> 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
>
>  local interface = {
>   method1 = method1;
>   method2 = method2;
>   --...
>   methodN = methodN;
>  }
>  factory = function()
>   return interface;
>  end
> end
>
> This way the functions are not upvalues to the scope where you create
> the interface table. They're just locals. The added advantage is that,
> if any of those functions calls any of the other functions, the called
> function IS an upvalue to the calling function, and therefore the call
> will be more efficient (because it does not require a table lookup).
> Furthermore, this is only a small change to your existing code, a nice
> workaround until you have time to refactor ;-)
>
> Hope this helps (and hope I'm right, from the top of my head...)
>
> Cheers,
> Mark
>
>
> 2008/8/21 Javier Guerra <javier@guerrag.com>:
>> On Thu, Aug 21, 2008 at 1:25 PM, Alexander Gladysh <agladysh@gmail.com> wrote:
>>> One of my most ugly objects now have more than 60 methods (yes, I
>>> know, I should refactor this abomination out immediately, but I just
>>> do not have time for it yet).
>>
>> put all methods in a separate file, prepend them with a module().
>> when you require() that file, you'll get a table with all non-local
>> functions.
>>
>> what module() does is mainly creating a new table, and setting it as
>> the environment.  after that, all non-local functions will populate
>> that table instead of the original _G.
>>
>> i've done this when i want a table with functions and don't want to
>> write something like:
>>
>> t = {
>>  f1=function(...) ... end,
>>  f2=function(..)  ... end,
>> .....
>> }
>>
>> with module() it's just
>>
>> module()
>>
>> function f1 (...)
>>  .....
>> end
>>
>> function f2 (...)
>>  .....
>> end
>>
>>
>> i really want to like the first option, since i know it's the most
>> 'functional', but the second one is a lot nicer to the eye, and using
>> module(), any non-local value gets stuffed into my table, so it works
>> great.
>>
>> --
>> Javier
>>
>