Functions
As mentioned in the chapter Functions, Yarn can access user-defined functions. A collection of functions is called a library and can be accessed through a DialogueRunner
.
Function Registration
For an easy example, let's modify the code used in the Quick Start to provide a simple pow
function to Yarn:
The following snippet is of special importance:
The first parameter of add_function()
is the name of the function as seen by Yarn, "pow"
in this case. The second parameter is the Rust function that will be called in the background. Here, we reference the function definition of fn pow(...)
, but you could also register a lambda.
This pow
function can now be called from the Yarn file like this:
Which will result in the following output:
Allowed Signatures
Custom functions need to follow some rules. Don't worry, they're pretty lax.
Their parameter and output types need to be primitive types or
String
Parameters are allowed to be references
Parameters can have the special type
YarnValue
, which stands for any input type. Additionally, functions are assumed to have no side effects. You can read the full list of requirements in the docs forYarnFn
.
Here are some examples of valid functions:
If you need functions that have side effects, e.g. for manipulating the game world, use custom commands instead.
Size constraints
Registered Rust functions can have a maximum of 16 parameters. If you need more, you can wrap parameters in tuples:
Tuples are treated as separate parameters when calling the function from Yarn:
Since tuples can be nested, you can use have potentially infinite parameters.
Last updated