Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[reference] Added macro docs #70

Merged
merged 7 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading