We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › How to send a function as function argument
Page Index Toggle Pages: 1
How to send a function as function argument ? (Read 572 times)
How to send a function as function argument ?
Dec 2nd, 2009, 11:42am
 
good afternoon to you all.

i'm trying to achieve something like this.

pseudo-code:

Ckeyboard k = new Ckeyboard();

void Setup()
{
   k.ALT_key(DoSomething());
}


void DoSomething()
{
     print('i did it');
}



public class Ckeyboard
{
  void ALT_key(Tfunc func)
   {
         // function func is executed here
         execute function;
   }
}

well, in the end function DoSomething() will be executed when i press ALT key.

note: code to catch key events is NOT in the class keyboard, but lets pretend is there.

anybody knows how can i pass functions as arguments?
Re: How to send a function as function argument ?
Reply #1 - Dec 2nd, 2009, 2:22pm
 
I'm fairly sure it's either fairly difficult or impossible to pass a function as an argument, but I'd be happy to be proved wrong.
Re: How to send a function as function argument ?
Reply #2 - Dec 2nd, 2009, 2:28pm
 
You cannot, and in languages allowing it, you pass the name of the function, not a call (with parentheses)...

In Java, you pass instead objects of a class implementing a known callback method:
Code:
Ckeyboard k = new Ckeyboard();

void setup()
{
k.ALT_key = new KeyboardHandler();
}

interface KeyboardListener
{
// Function to implement (mandatory)
void Handle(KeyKind kk);
}

class KeyboardHandler implements KeyboardListener
{
void Handle(KeyKind kk)
{
print('i did it with ' + kk);
}
}


public class Ckeyboard
{
KeyboardListener ALT_key;

void KeyPressed()
{
if (key == ALT)
{
// function func is executed here
ALT_key.Handle(key);
}
}
}

That's rough sketchy pseudo-code, of course.
Re: How to send a function as function argument ?
Reply #3 - Dec 2nd, 2009, 2:49pm
 
thanks guys, i'll what i can do with this.
Page Index Toggle Pages: 1