lua-users home
lua-l archive

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


On Tuesday 22 June 2004 18:55, O'Riain, Colm wrote:
> My apologies if this has been covered recently on this list but I
> couldn't find it in the archive.
> I'm trying to pass a table containing functions as a parameter as
> follows:
> [...]
> where myFunc and anotherFunc are pre-declared functions and bigFunc is a
> function which _might_ call the 3rd entry in each subTable in myTable.
> The problem is that on calling bigFunc, the 3rd parameter of each
> subTable is always evaluated and the function is always called
> immediately, which is not desirable. Is there a way to suppress
> evaluation at call time or am I looking at this assways?

A function is always called as soon as you use any function call syntax. In 
your example, the function is being called when the table is created, not 
when bigFunc is called. There are two possible solutions:

1) Closures:

local myTable = 
{
            {'hello', nil, function() myFunc(3,4) end },
            {'not now'', nil, function() print('the end is nigh') end },
            {'maybe later', nil, function() anotherFunc(5,6) end }
}

This is the most flexible, fastest, and most logical approach. You can put 
anything you want inside the closure, and all bigFunc has to do is call it. 
You might not like the extra syntax though.

2) Tables:

local myTable = 
{
            {'hello', nil, myFunc, {3,4} },
            {'not now'', nil, print, {'the end is nigh'} },
            {'maybe later', nil, anotherFunc, {5,6} }
}

This is a slight variation on your scheme. The advantage of keeping the 
function name separate from its arguments is that each function can now be 
called simply with:

local myRecord = myTable[myIndex]
myRecord[3](unpack(MyRecord[4]))

-- Jamie Webb