A function in programming is a collection of code lines (a block) which you can run on-command anywhere in your script by executing the function. We usually refer to executing a function as calling the function.
Functions are extremely powerful because they can be run multiple times, and they can both receive information, which is used when executing, and also return information, aka send information back. They help to reduce repeated code (thereby reducing errors that may arise from copying or rewriting out the code many times, and making it easier to correct mistakes in your coding logic) and are very helpful for performing complex tasks.
You’ve likely already seen or used functions in Ren’Py before, as it has many functions built in. For example, renpy.music.play
is a function. It takes in information such as the file path of the file to play, and the result of calling renpy.music.play
is that an audio file is played. renpy.input
is also a function, which takes in information like a prompt to display to the player (e.g. “What is your name?”) and returns the text that the player wrote as a string so that you can write something like $ name = renpy.input("What is your name?")
to get the player’s name.
In Ren’Py, functions can only be written in pure Python, inside an init python:
block. They can then be called in your script like $ my_function()
.