User Tools

Site Tools


afunc

Table of Contents

afunc

anonymous function - allows for the definition and execution of a nameless function within an execution compound statement.

syntax


afunc([parameterlist])

[variable declarations]

do

[statements]

return expression

end


  • parameterlist is an optional list of one or more variables, separated by commas, that will be passed to the function
  • variable declarations are optional dim or const statements of variables to be used within the function
  • expression is the return value of the function

See also decl, func, sub

details

An anonymous function has its own scope and can be placed within any execution compound statement do..end. It does not have a name as identifier.

Parameters are passed from the calling code block without type definition and are always passed by reference.

Local variables can be declared inside an anonymous function just as with normal functions and subroutines.

The return value can be an expression assigned to the return statement. The type returned by an anonymous function depends on the expression in the return statement. For example, if an anonymous function returns a string expression, it must be assigned to a string variable. Numerical expressions are implicitly converted, including single variables, unless the option strict clause is set at the beginning of the program, in which case the variable returned must match the variable to which the anonymous function is assigned.

examples

In this example an anonymous function is used to add the number 1 to 7 and return the result.

' SharpBASIC anonymous function programming example
' -------------------------------------------------
option strict;

incl "lib/sys.sbi";

dim a, n: int;

main do
  n = 7;
  ' create scope and use copy of n
  a = afunc(n)
    dim i: itr;
    dim r: int = 0;
  do
    for i = 1 to n :++ do
      r:+i;
    end
    return r;
  end
  print(a);
end
Output:

28


In the following example in a subroutine a record instance is passed to an anonymous function that has a local constant declared to calculate a volume and multiply it by a factor 10. Note the use of the compound with-statements to shorten identifier notation.

' SharpBASIC anonymous function programming example
' -------------------------------------------------
option strict;

incl "lib/sys.sbi";

record rSize is
  x: int;
  y: int;
  z: int;
end

decl sub test();

main do
  call test;
end

sub test()
  dim size: rSize;
  dim vol: int;
do
  with size do
    .x = 3;
    .y = 7;
    .z = 5;

    vol = afunc(size)
      const fac = 10;
    do
      with size do
        return .x * .y * .z * fac;
      end
    end

    print(.x);
    print(.y);
    print(.z);
  end
  print(vol);
end
Output:

3

7

5

1050

afunc.txt · Last modified: 2023/07/27 12:39 by admin