Call: Difference between revisions

From Kolmafia
Jump to navigation Jump to search
Fix formatting, add Scope section
Highlight the callbacks themselves, which should make the explanation more intuitive
 
Line 33: Line 33:
For example, executing the following ASH code will result in an error, because the <code>func_inside_bar()</code> function is not visible from within <code>foo()</code>:
For example, executing the following ASH code will result in an error, because the <code>func_inside_bar()</code> function is not visible from within <code>foo()</code>:


<syntaxhighlight lang="d" line highlight="3">
<syntaxhighlight lang="d" line highlight="7-9">
void foo( string callback ) {
void foo( string callback ) {
   // foo() cannot see func_inside_bar()
   // foo() cannot see func_inside_bar()
Line 51: Line 51:
However, the following code will run successfully:
However, the following code will run successfully:


<syntaxhighlight lang="d" line highlight="5">
<syntaxhighlight lang="d" line highlight="2-4">
void foo( string callback ) {
void foo( string callback ) {
   void func_inside_foo( int arg ) {
   void func_inside_foo( int arg ) {

Latest revision as of 06:52, 23 February 2021

Syntax: call [type] <identifier>( param, ... );

type is an optional parameter which must match the return value of the function. If not specified, type defaults to void.

For instance, the following ASH code:

int foo( int a, int b ) {
   return a + b;
}

String a = "foo";
float c = call float a( 2, 3 );
print( "c = " + c );

a = "print";
call a( "print 1" );
print( "done" );

will output the following to the CLI:

c = 5.0
print 1
done

Scope

call can only execute functions that are visible in the scope of the call statement.

For example, executing the following ASH code will result in an error, because the func_inside_bar() function is not visible from within foo():

void foo( string callback ) {
   // foo() cannot see func_inside_bar()
   call void callback( 123 );
}

void bar() {
   void func_inside_bar( int arg ) {
      print( arg );
   }
   foo( "func_inside_bar" );
}

bar(); // Error: Function 'func_inside_bar( int )' undefined.

However, the following code will run successfully:

void foo( string callback ) {
   void func_inside_foo( int arg ) {
      print( arg );
   }
   call void callback( 123 );
}

void bar() {
   // Although bar() cannot see func_inside_foo(),
   // it can still pass its name to foo()
   foo( "func_inside_foo" );
}

bar(); // Prints "123"