lua-users home
lua-l archive

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

You could simply move the table construction outside of the factory
function, to the same scope as the local functions:

local factory
 local method1 = function(self)
   print("method1", tostring(self))

 local method2 = function(self)
   print("method2", tostring(self))

 local methodN = function(self)
   print("methodN", tostring(self))

 local interface = {
   method1 = method1;
   method2 = method2;
   methodN = methodN;
 factory = function()
   return interface;

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...)


2008/8/21 Javier Guerra <>:
> On Thu, Aug 21, 2008 at 1:25 PM, Alexander Gladysh <> 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