Calling a function with a FunctionPointer

Hi,
Is there a way in Lua to call a function using a function pointer?

for example

local function testMeWithAFunction( \_theFunction\_ )  
 --How to call this function here ?  
end  
  
local function printHello ()  
 print ("Hello")  
end  
  
testMeWithAFunction ( printHello )  
  

cheers,
[import]uid: 3826 topic_id: 7494 reply_id: 307494[/import]

I’m not exactly sure I’m getting what you’re asking, but I think I might…

If you pass the function as an argument to another function, you simply call the argument. However, if it is a local function, it must be defined ABOVE wherever you intend to call it.

So for example…

[blockcode]
local function testMeWithAFunction( _theFunction )
– The following won’t work, because at this point, printHello() doesn’t exist
_theFunction()
end

local function printHello ()
print (“Hello”)
end

testMeWithAFunction ( printHello )
[/blockcode]

However, if you do it this way, things will work:

[blockcode]
local function printHello()
print(“Hello”)
end

local function testMeWithAFunction( _theFunction )
– the following WILL work, because printHello() DOES exist at this point:
_theFunction()
end

testMeWithAFunction( printHello )
[/blockcode] [import]uid: 7849 topic_id: 7494 reply_id: 26562[/import]

Or you could do it exactly the way I stated in my first example, but remove the ‘local’ part when defining your printHello() function… [import]uid: 7849 topic_id: 7494 reply_id: 26563[/import]

Hi Jon,
I guess it was \_theFunction\_() that I was after, I had a suspicion about it as it was the only logical explanation, but did not see any samples using that. so wanted to be certain.

cheers,

Jayant C Varma [import]uid: 3826 topic_id: 7494 reply_id: 26564[/import]

jon,

in that instance you wouldn’t particularly want to remove the local completely. you could just predefine it

[lua]local printHello – forward reference

local function testMeWithAFunction( _theFunction )
–this works now
_theFunction()
end

function printHello () – still local, just defined now
print (“Hello”)
end

testMeWithAFunction ( printHello )[/lua]

this is more a required approach when you need 2 functions to call each other

actually though …the original example does work. since you don’t call _theFunction() till after printHello has been defined

[lua]local function testMeWithAFunction( _theFunction )
–this does work!
_theFunction()
end

local function printHello ()
print (“Hello”)
end

testMeWithAFunction ( printHello )[/lua] [import]uid: 6645 topic_id: 7494 reply_id: 26611[/import]

@jmp909: Great addition with the forward reference stuff… very useful! [import]uid: 7849 topic_id: 7494 reply_id: 26615[/import]