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)
    • visited returns a boolean value of true if the node with the title of node_name has been entered and exited at least once before, otherwise returns false. Will return false if node_name doesn’t match a node in project.
  • visited_count(string node_name)
    • visted_count returns a number value of the number of times the node with the title of node_name has been entered and exited, otherwise returns 0. Will return 0 if node_name doesn’t match a node in project.
  • random()
    • random returns a random number between 0 and 1 each time you call it.
  • random_range(number a, number b)
    • random_range returns a random integer between a and b, inclusive.
  • dice(number sides)
    • dice returns a random integer between 1 and sides, inclusive. For example, dice(6) returns a number between 1 and 6, just like rolling a six-sided die.
  • round(number n)
    • round rounds n to the nearest integer.
  • round_places(number n, number places)
    • round_places rounds n to the nearest number with places decimal points.
  • floor(number n)
    • floor rounds n down to the nearest integer, towards negative infinity.
  • ceil(number n)
    • ceil rounds n up to the nearest integer, towards positive infinity.
  • inc(number n)
    • inc rounds n up to the nearest integer. If n is already an integer, inc returns n+1.
  • dec(number n)
    • dec rounds n down to the nearest integer. If n is already an integer, dec returns n-1.
  • decimal(number n)
    • decimal returns the decimal portion of n. This will always be a number between 0 and 1. For example, decimal(4.51)will return 0.51.
  • int(number n)
    • int rounds n down 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 dice function, the random_range function, and the visited and visited_count functions.

Next, put everything you’ve learned so far together.

Stay in the Know

Join our mailing list to stay up-to-date on what’s new in Yarn Spinner