Functions
A Function lets a Yarn Script ask your game for a value, like how many coins the player has, or whether they’re carrying a key. You call it by name, with any arguments in brackets, and your game sends back the answer:
title: FunctionsDemo
---
<<if has_item("brass key")>>
Rosa: Good, you've got the key.
<<else>>
Rosa: You'll need a key to get up the stairs.
<<endif>>
<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.
===The dialogue uses the value and carries on. To have your game do something, use a Command.
sequenceDiagram
participant R as Dialogue Runner
participant G as Your game code
Note over R: #60;#60;if has_item("brass key")#62;#62;
R->>G: _has_item("brass key")
G-->>R: returns false
Note over R: Shows "You'll need a key to get up the stairs."
Note over R: #60;#60;set $coin_total to coin_count()#62;#62;
R->>G: _coin_count()
G-->>R: returns 15
Note over R: Shows "You've got 15 coins."Using Functions in Yarn
You can use a Function anywhere Yarn expects a value:
- in a condition:
<<if has_item("brass key")>>, - in a
<<set>>:<<set $coin_total to coin_count()>>, - in an expression with other values:
<<if coin_count() >= 10>>.
Put text arguments in double quotes, like "brass key". Numbers, true and false, and variables go in as they are: has_item($chosen_item).
A Function can go directly inside a line, like Rosa: You've got {coin_count()} coins. When the Yarn Project is imported, the addon finds your Functions and tells the compiler what each one returns. The compiler uses that to work out how to show the value.
If the addon can’t find a Function’s return type, a Function used directly inside a line won’t compile, and you’ll see “Can’t determine the type of the expression”. That happens when:
- the addon can’t find the Function’s script, because it isn’t in the Yarn Project’s folder or in a scene that uses the Yarn Project, or it’s outside the folder set in the Ysls Scan Path import option (see The .ysls.json file),
- the Function’s method doesn’t say what it returns, like
func _coin_count():instead offunc _coin_count() -> int:, or it returns aSignal, or it’s a lambda, - the Function is added by an addon, which the plugin skips unless you list it (see Commands and Functions in an addon),
- the Yarn Project’s Generate Ysls import option is off and the project is compiled with
yscinstead of the built-in compiler. The built-in compiler gets your Functions’ types whether the option is on or off.
In a version 5 Yarn Project, the compiler has to know about every Function, wherever it’s used. For a Function the plugin can’t find a return type for, you’ll see “no declaration found” instead, and the error says what to change.
Fix whichever applies, or store the value in a variable first and put the variable in the line:
<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.Writing a Function
Functions the Dialogue Runner finds by itself
Give a static method a name that starts with _yarn_function_, and the rest of the name is the Function’s name in Yarn:
static func _yarn_function_shout(text: String) -> String:
return text.to_upper()The Dialogue Runner finds these methods in the same places it finds Commands: in scripts with a class_name, in scripts attached to nodes in the running scene, and in autoloads. See Where the Dialogue Runner looks.
A static method can be called from anywhere. A method in an autoload can be either.
Functions on a node
A _yarn_function_ method that isn’t static belongs to the script on a node. In Yarn, the first argument is the name of the node to call it on, in double quotes:
@export var hit_points := 10
func _yarn_function_health() -> int:
return hit_pointsAlice has {health("Alice")} hit points, and Bob has {health("Bob")}.The Dialogue Runner finds the node the same way as for a Command on a node. It then checks that the node, or one of its children, has the script. If there’s no node with that name, or it doesn’t have the script, the Dialogue Runner logs an error and stops the dialogue.
If the script’s class has a converter, the first argument goes to the converter instead, and the method is called on the object it returns.
The .ysls.json lists the node as the Function’s first parameter, and VS Code expects a name there.
Functions that use your game’s state
A static method can’t read the variables on a node, like an inventory. For a Function that needs to, add it to the Dialogue Runner with add_function():
@export var dialogue_runner: YarnDialogueRunner
var _inventory: Array[String] = ["lantern"]
var _coins := 15
func _ready():
dialogue_runner.add_function("has_item", _has_item)
dialogue_runner.add_function("coin_count", _coin_count)
func _has_item(item_name: String) -> bool:
return item_name in _inventory
func _coin_count() -> int:
return _coinsstatic method couldn’t see these.has_item("brass key") in Yarn calls this. It returns a bool, which an <<if>> can use.coin_count() returns a number.Pass a named method, like _has_item, so the Dialogue Runner can see its parameters. A lambda has no parameter types, and its arguments aren’t converted. Adding a Function with a lambda still works, but it’s deprecated, and the Dialogue Runner logs a warning. If you do pass a lambda, give the number of arguments it takes as a third argument: dialogue_runner.add_function("double", func(n): return n * 2, 1).
To remove a Function, call dialogue_runner.remove_function("has_item"). To add a Function to every Dialogue Runner in your game, call YarnSpinner.register_function(), with the same arguments, before the Dialogue Runners start.
Two Functions can’t have the same name. If a second one uses a name that’s already taken, the Dialogue Runner logs an error and ignores it.
Values going in and out
A Function has to return one of the kinds of value Yarn understands:
| Return type | In Yarn |
|---|---|
bool | true or false. |
int or float | A number. |
String | Text. |
If a Function returns something else, or returns nothing, the Dialogue Runner logs an error and stops the dialogue.
Arguments are converted to the types of the method’s parameters. A Yarn number becomes an int or float, and true and false become a bool. A parameter without a type gets the value as it is. Parameters with default values can be left out.
A parameter can be a Yarn enum from the generated variables class, like MyVariables.FoodType. Yarn passes the enum’s value, and your method gets the matching case, such as MyVariables.FoodType.APPLE. See Yarn enums.
A Function can’t return a Yarn enum. If its return type is an enum, the Dialogue Runner logs an error and stops the dialogue. Return the enum’s value instead, like "apple", with a String or number return type. You can store it in a variable declared as text and compare it with string($your_enum_variable). The Custom Actions sample does this.
To take any number of arguments, end the method’s parameters with ... and a name. The extra arguments arrive as an Array, and the built-in plural() and ordinal() work this way:
func _total(...values: Array) -> float:
var sum := 0.0
for value in values:
sum += value
return sumtotal(1, 2, 3) returns 6. The ... parameter has to be the last one.
GDScript can’t give a ... parameter a type. The addon can’t tell the compiler what the extra arguments are, and leaves the Function undeclared. In a version 4 Yarn Project, the compiler works out the types from how you call it, but only outside lines. In a version 5 Yarn Project, every Function has to be declared. Add one to a .ysls.json file in the project’s definitions, giving the extra arguments a type with "isParamsArray": true. The built-in plural() and ordinal() are already declared.
A parameter can also be one of your own types, like an inventory item, if you add a converter for it. The text from the Yarn Script goes to the converter, and your method gets what it returns. See Your own types.
Functions that wait
A Function can take as long as it needs, for example to let the player pick an item. Use await in the method, and give it the type of the value it ends up returning. The dialogue pauses until it returns:
func _ready():
dialogue_runner.add_function("pick_item", _pick_item)
func _pick_item() -> String:
var item = await inventory_menu.item_chosen
return item.name<<set $chosen to pick_item()>>
Rosa: A {$chosen}? Thanks!Write the return type the value will have, like -> String, not -> Signal. Returning a Signal works while the game runs, but the compiler can’t tell what it will carry, and a version 5 Yarn Project won’t compile calls to it.
Functions used in smart variables or in when: headers still have to return straight away. If one of those waits, the Dialogue Runner logs an error.
If the last parameter of a Function is a YarnCancellationToken, the Dialogue Runner passes one in. A Function that’s waiting can use it to give up early, because it’s cancelled when the dialogue stops. request_hurry_up() and request_next_content() don’t affect it. The exception is a Function called while a Command is running, which shares the Command’s token. See Async and Cancellation.
If a Function gets the wrong number of arguments, or one can’t be converted, the Dialogue Runner logs an error and stops the dialogue.
Built-in Functions
These Functions are always available:
| Function | What it returns |
|---|---|
visited("NodeName") | true if the node has been run before. |
visited_count("NodeName") | How many times the node has been run. |
random() | A random number between 0 and 1. |
random_range(1, 6) | A random whole number from the first number to the second, including both. |
dice(6) | A random whole number from 1 to the number you give it, like rolling a die. |
round(n), floor(n), ceil(n) | The number rounded to the nearest whole number, down, or up. |
min(a, b), max(a, b) | The smaller or larger of two numbers. |
For maths there are random_range_float, round_places, inc, dec, decimal, int, abs, sign, clamp, lerp, inverse_lerp, smoothstep, pow, sqrt, wrap and mod. For converting between types there are string, number and bool. For text there are format, format_invariant, length, uppercase, lowercase, first_letter_caps, plural and ordinal. has_any_content("GroupName") checks whether a node group has a node whose conditions pass.
abs, sign, clamp, lerp, inverse_lerp, smoothstep, pow, sqrt, wrap, mod, length, uppercase, lowercase, plural, ordinal, has_any_content and first_letter_caps. A Yarn Script that uses them won’t compile in Yarn Spinner for Unity, or in other tools that don’t have them. If you share your Yarn Scripts with another engine, don’t use them.Autocomplete in VS Code
The Yarn Spinner extension for VS Code suggests your Functions as you type, along with what they return. It reads them from the project’s .ysls.json file, which the addon writes for you. The file includes Functions you add with add_function(). This covers add_function() called on a Dialogue Runner variable, and called on its own in a script that extends the Dialogue Runner. The file also lists the built-in Functions above that only Yarn Spinner for Godot has, which stops VS Code marking them as unknown. See The .ysls.json file.
The demo scene
title: FunctionsDemo
---
<<declare $lamp_days = 0>>
<<set $lamp_days to days_since_lamp_lit()>>
Rosa: The lamp's been out for {$lamp_days} days.
<<if has_item("brass key")>>
Rosa: Good, you've got the key.
<<else>>
Rosa: You'll need a key to get up the stairs.
<<endif>>
<<declare $coin_total = 0>>
<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.
<<if coin_count() >= 10>>
Rosa: That's enough to buy oil for the lamp.
<<endif>>
<<declare $sign_text = "">>
<<set $sign_text to shout("keep out")>>
Rosa: The sign on the door says "{$sign_text}".
===extends Node2D
@export var dialogue_runner: YarnDialogueRunner
@export var call_log: RichTextLabel
@export var inventory_label: Label
var _inventory: Array[String] = ["lantern"]
var _coins := 15
static var _log: RichTextLabel
func _ready():
_log = call_log
dialogue_runner.add_function("days_since_lamp_lit", _days_since_lamp_lit)
dialogue_runner.add_function("has_item", _has_item)
dialogue_runner.add_function("coin_count", _coin_count)
_update_inventory()
static func _log_function(call_text: String, result: Variant) -> void:
var shown := '"%s"' % result if result is String else str(result)
_log.append_text("[color=#7fc4e8]Function[/color] %s → %s\n" % [call_text, shown])
func _update_inventory() -> void:
var text := "Inventory\n"
for item in _inventory:
text += "• " + item + "\n"
text += "• %d coins" % _coins
inventory_label.text = text
# Functions added in _ready
func _days_since_lamp_lit() -> int:
var days := 12
_log_function("days_since_lamp_lit()", days)
return days
func _has_item(item_name: String) -> bool:
var result := item_name in _inventory
_log_function('has_item("%s")' % item_name, result)
return result
func _coin_count() -> int:
_log_function("coin_count()", _coins)
return _coins
# A Function the Dialogue Runner finds by itself
static func _yarn_function_shout(text: String) -> String:
var result := text.to_upper()
_log_function('shout("%s")' % text, result)
return resultstatic variable so the static Function can write to it too. This is only for the demo.shout is static and named _yarn_function_shout, and the Dialogue Runner finds it by itself.days_since_lamp_lit() returns a number.has_item() returns a bool.coin_count() returns the number of coins.shout() returns its text in capitals. Being static, it can’t read this node’s variables.