Previous section To contents

4.2.6 function

When indexing an object on a string, and that string is the name of a function in the object a function is returned. Despite its name, a function is really a function pointer.

fig 4.6
When the function pointer is called, the interpreter sets this_object() to the object in which the function is located and proceeds to execute the function it points to. Also note that function pointers can be passed around just like any other data type:
int foo() { return 1; }
function bar() { return foo; }
int gazonk() { return foo(); }
int teleledningsanka() { return bar()(); }
In this example, the function bar returns a pointer to the function foo. No indexing is necessary since the function foo is located in the same object. The function gazonk simply calls foo. However, note that the word foo in that function is an expression returning a function pointer that is then called. To further illustrate this, foo has been replaced by bar() in the function teleledningsanka.

For convenience, there is also a simple way to write a function inside another function. To do this you use the lambda keyword. The syntax is the same as for a normal function, except you write lambda instead of the function name:

lambda ( types ) { statements }
The major difference is that this is an expression that can be used inside an other function. Example:
function bar() { return lambda() { return 1; }; )
This is the same as the first two lines in the previous example, the keyword lambda allows you to write the function inside bar.

Note that unlike C++ and Java you can not use function overloading in Pike. This means that you cannot have one function called 'foo' which takes an integer argument and another function 'foo' which takes a float argument.

This is what you can do with a function pointer.

calling ( f ( mixed ... args ) )
As mentioned earlier, all function pointers can be called. In this example the function f is called with the arguments args.
string function_name(function f)
This function returns the name of the function f is pointing at.
object function_object(function f)
This function returns the object the function f is located in.
int functionp(mixed f)
This function returns 1 if f is a function, 0 otherwise. If f is located in a destructed object, 0 is returned.
function this_function()
This function returns a pointer to the function it is called from. This is normally only used with lambda functions because they do not have a name.

Previous section To contents