Skip to content

Commit

Permalink
[reference] Added macro docs (#70)
Browse files Browse the repository at this point in the history
* Macro docs


---------

Co-authored-by: Cam Swords <[email protected]>
Co-authored-by: Tim Zakian <[email protected]>
  • Loading branch information
3 people authored Jul 22, 2024
1 parent 05df173 commit 3004cf5
Show file tree
Hide file tree
Showing 3 changed files with 783 additions and 1 deletion.
29 changes: 28 additions & 1 deletion reference/src/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Functions are declared with the `fun` keyword followed by the function name, typ
parameters, a return type, and finally the function body.

```text
<visibility>? <entry>? fun <identifier><[type_parameters: constraint],*>([identifier: type],*): <return_type> <function_body>
<visibility>? <entry>? <macro>? fun <identifier><[type_parameters: constraint],*>([identifier: type],*): <return_type> <function_body>
```

For example
Expand Down Expand Up @@ -147,6 +147,33 @@ module a::m_test {
}
```

### `macro` modifier

Unlike normal functions, `macro` functions do not exist at runtime. Instead, these functions are
substituted inline at each call site during compilation. These `macro` functions leverage this
compilation process to provide functionality beyond standard functions, such as accepting
higher-order _lambda_-style functions as arguments. These lambda arguments, also expanded during
compilation, allow you to pass parts of the function body to the macro as arguments. For instance,
consider the following simple loop macro, where the loop body is supplied as a lambda:

```move
macro fun ntimes($n: u64, $body: |u64| -> ()) {
let n = $n;
let mut i = 0;
while (i < n) {
$body(i);
i = i + 1;
}
}
fun example() {
let mut sum = 0;
ntimes!(10, |x| sum = sum + x );
}
```

See the chapter on [macros](./macros.md) for more information.

### Name

Function names can start with letters `a` to `z`. After the first character, function names can
Expand Down
Loading

0 comments on commit 3004cf5

Please sign in to comment.