On this Page
Functions
A function is a block of code that provides a value to your Yarn scripts, which you can use in if statements, or store in variables.
In Yarn scripts, functions perform two main kinds of task:
- Functions let you get values that change over time, or that depend on other values. For example, the
randomfunction returns a different random number every time you call it. - Functions let you get data from your game back into your scripts.
Built-in Functions
Yarn Spinner provides the following built-in functions:
visited(string node_name)visitedreturns a boolean value oftrueif the node with the title ofnode_namehas been entered and exited at least once before, otherwise returnsfalse. Will returnfalseifnode_namedoesn’t match a node in project.
visited_count(string node_name)visted_countreturns a number value of the number of times the node with the title ofnode_namehas been entered and exited, otherwise returns0. Will return0ifnode_namedoesn’t match a node in project.
random()randomreturns a random number between 0 and 1 each time you call it.
random_range(number a, number b)random_rangereturns a random integer betweenaandb, inclusive.
dice(number sides)dicereturns a random integer between 1 andsides, inclusive. For example,dice(6)returns a number between 1 and 6, just like rolling a six-sided die.
round(number n)roundroundsnto the nearest integer.
round_places(number n, number places)round_placesroundsnto the nearest number withplacesdecimal points.
floor(number n)floorroundsndown to the nearest integer, towards negative infinity.
ceil(number n)ceilroundsnup to the nearest integer, towards positive infinity.
inc(number n)incroundsnup to the nearest integer. Ifnis already an integer,increturnsn+1.
dec(number n)decroundsndown to the nearest integer. Ifnis already an integer,decreturnsn-1.
decimal(number n)decimalreturns the decimal portion ofn. This will always be a number between 0 and 1. For example,decimal(4.51)will return0.51.
int(number n)introundsndown to the nearest integer, towards zero.
For example, you can use functions inside if statements, and in regular lines, as they largely behave like variables. For example:
// Inside an if statement:
<<if dice(6) == 6>>
You rolled a six!
<<endif>>
// Inside a line:
Gambler: My lucky number is {random_range(1,10)}!
- Write some yarn using functions! We recommend the
dicefunction, therandom_rangefunction, and thevisitedandvisited_countfunctions.