lua-users home
lua-l archive

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


Thanks to Jamie and Virgil for your quick answers. I had tried closures
before but when I use closures, nothing happens when I call that 3rd
parameter:

function bigFunc(convTable)   
	...
	
	if (convTable[1][3] ~= nil) then
		print('calling script on line 1 -
',convTable[1][3],'type = ',type(convTable [1][3]))
   		convTable[1][3]
	end

	...	
end

This results in the following output

calling script on line  1        -      function: 0x163e2d0      - type
=       
function      


but the actual function is not called. I'm using Lua 4.0. Am I calling
it correctly? 

Thanks for the nicer presentation on the table avenue of approach. 

C.
                                                           
-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Jamie Webb
Sent: Tuesday, June 22, 2004 11:53 AM
To: Lua list
Subject: Re: Suppress Function Evaluation

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