renpy/doc/reference/The Ren'Py Language - Ren'Py

documentation index ◦ reference manual ◦ function index

# The Ren'Py Language

This section describes the Ren'Py language, and the functions found in that language.

## Script, Line, and Block Structure

Ren'Py scripts consist of one or more .rpy files. These script files may be read in any order, and all of them together make up a Ren'Py script. Please see The Ren'Py Runtime Environment for information about where Ren'Py searches for .rpy files.

Each of these files is divided into a series of logical lines. The first logical line of a file begins at the start of a file, and another logical line begins after each logical line ends, until the end of the file is reached. By default, a logical line is terminated by the first newline encountered. However, a line will not terminate if any of the following are true:

- The newline is immediately preceded by a backslash. In this case, the backslash is removed, and the newline is ignored.
- An opening parenthesis, bracket, or brace has been encountered without encountering the corresponding closing character.
- The newline occurs within a string.

Ren'Py script files also can include comments. A comment begins with a hash mark that is not contained within a string, and continues to, but does not include, the next newline character. Some examples are:

    # This line contains only a comment.
    scene bg whitehouse  # This line contains a statement as well.

If, after eliminating comments, a logical line is empty, that logical line is ignored.

Logical lines are then combined into blocks. Two logical lines are in the same block if the lines have the same indentation preceding them, and no logical line with a lesser amount of indentation occurs between the two lines. Indentation may only consist of spaces, not tabs. In the following example:

    line 1
        line a
        line b
    line 2
        line c
        line d

In this example, here are three blocks. One block contains lines 1 and 2, another lines a and b, and the third contains lines c and d. This example can also serve to illustrate the concept of a block associated with a line. A block is associated with a line if the block starts on the next logical line following the line. For example, the block containing lines a and b is associated with line #

There are three kinds of blocks in an Ren'Py program. The most common is a block containing Ren'Py statements. Blocks may also contain menuitems or python code. The top-level block (the one that contains the first line of a file) is always a block of Ren'Py statements.

## Syntax Constructs

Before we can describe Ren'Py statements, we must first describe a number of syntactic constructs those statements are built out of. In this subsection, we describe such constructs.

Keywords are words that must literally appear in the source code. They're used ito introduce statements, or to delimit parts of statements. You'll see keywords throughout the descriptions of statements. In grammar rules, keywords are in quotes. The keywords used by Ren'Py are:

    at
    behind
    call
    elif
    else
    expression
    hide
    if
    image
    init
    jump
    label
    menu
    onlayer
    pass
    python
    return
    scene
    set
    show
    while
    with
    zorder

A name consists of a letter or underscore (_) followed by zero or more letters, numbers, or underscores. For this purpose, unicode characters between U+00a0 and U+fffd are considered to be letters. A name may not be a keyword.

A simple_expression is a Python expression that starts with a name, a string, or any Python expression in parenthesis. This may be followed by any number of the following:

- A dot followed by a name.
- A parenthesized python expression.

A python_expression is an arbitrary python expression that may not include a colon. These expressions are generally used to express the conditions in the if and while statements.

An image_name consists of one or more names, separated by spaces. The first name in an image_name is known as the image_tag.

    image_spec -> image_name ("as" name)? ( "onlayer" name)? ( "at" transform_list )? ( "with" simple_expression )? ("behind" name_list)?

An image_spec consists of an image name, followed by zer or more of the following clauses (in any order, provided each clause is only given once).

- an `as` clause giving an alternative tag for the image.
- an `onlayer` clause, followed by a name giving the layer this image is on.
- an `at` clause with a comma-separated list of simple_expressions that evaluate to functions that transform displayables to displayables,
- a `with` clause. (see the with statement for details.)
- a `behind` clause, with a comma-separated list of names, which are interpreted as image tags the image will be displayed behind.

    image_spec -> ("image | "expression") simple_expression ("as" name)? ( "onlayer" name)? ( "at" transform_list )? ( "with" simple_expression )? ("behind" name_list)?

Alternatively, an image may be specified as the keyword "image" followed by a simple expression that is interpreted as a displayable. This allows images to be defined inline. Note that an "as" clause is recommended if it is desired to hide the image. All clauses are interpreted in the same way. "expression" may be used as a synonym for "image" here.

#### Name Munging

Before parsing a file, Ren'Py looks for names of the form _'_'_word, where word does not contain an _'_. It munges these names in a filename-specific manner, generally ensuring that they will not conflict with the same name in other files. For example, in the file script.rpy, _'_v is munged into _'_'_script_'_v.

Names beginning with an odd number of underscores are reserved for Ren'Py, while those beginning with an even number of underscores can safely be used in scripts.

#### Grammar Rules

We will be giving grammar rules for some of the statements. In these rules, a word in quotes means that that word is literally expected in the script. Parenthesis are used to group things together, but they don't correspond to anything in the script. Star, question mark, and plus are used to indicate that the token or group they are to the right of can occur zero or more, zero or one, or one or more times, respectively.

If we give a name for the rule, it will be separated from the body of the rule with a crude ascii-art arrow (->).

## Statements

### Call Statement

The `call` statement is used to transfer control to the statement with the given name. It also pushes the name of the statement following this one onto the call stack, allowing the return statement to return control to the statement following this one.

    call_statement -> "call" name ( "from" name )?
    call_statement -> "call" "expression" simple_expression ( "from" name )?

    call_statement -> "call" name "(" arguments ")" ( "from" name )?
    call_statement -> "call" "expression" simple_expression "(" arguments ")" ( "from" name )?

If the `expression` keyword is present, the expression is evaluated, and the string so computed is used as the name of the statement to call. If the `expression` keyword is not present, the name of the statement to call must be explicitly given.

If the optional `from` clause is present, it has the effect of including a label statement with the given name as the statement immediately following the call statement. An explicit label is required here to ensure that saved games with return stacks can return to the proper place when loaded on a changed script. From clauses should be included for all calls in released games.

As from clauses may be distracting when a game is still under development, we provide with Ren'Py a program, called `add_from`, that adds from clauses to all bare calls in any game directory. It can be found in `tools/add_from`, although it needs to be run from the base directory. The easiest way to do this on windows is by running `tools/game_add_from.bat`. It should be run before a final release of your game is made. Be sure to make a backup of your game directories before running add_from. Also note that `add_from` produces .bak files for all files it can change, so delete them when you're satisfied that everything worked.

    e "First, we will call a subroutine."

    call subroutine from _call_site_1

    # ...

    label subroutine:

        e "Next, we will return from the subroutine."

        return

The call statement may take arguments, which are processed as described in PEP 3012. If the return statement returns a value, that value is stored in the _return variable, which is dynamically scoped to each context.

### Hide Statement

The `hide` statement is used to hide an image from the screen, based on a supplied image_spec.

    hide_statement -> "hide" image_spec

A `hide` statement operates on the layer supplied in the `onlayer` clause of the image_spec, defaulting to "master" if no such clause has been supplied. It finds an image beginning with the image tag of the image name in the image_spec, and removes it from that layer.

Please note that the `hide` statement is rarely used in practice. Show can be used by itself when a character is changing emotion, while `scene` is used to remove all images at the end of a scene. Hide is only necessary when a character leaves before the end of a scene.

### If Statement

The `if` statement is used to conditionally execute a block of statements.

    if_statement -> "if" python_expression ":"
    elif_clause -> "elif" python_expression ":"
    else_clause -> "else" ":"

The `if` statement is the only statement which consists of more than one logical line in the same block. The initial `if` statement may be followed by zero or more `elif` clauses, concluded with an optional `else` clause. The expression is evaluated for each clause in turn, and if it evaluates to a true value, then the block associated with that clause is executed. If no expression evaluates to true, then the block associated with the `else` clause is executed. (If an `else` clause exists, execution immediately continues with the next statement.) In any case, at the end of the block, control is transferred to the statement following the if statement.

    if points >= 10:

       e "Congratulations! You're getting the best ending!"

    elif points >= 5:

       e "It's the good ending for you."

    else:

       e "Sorry, you're about to get the bad ending."

### Image Statement

The `image` statement is used to declare images to Ren'Py. Image statements can only appear in init blocks.

    image_statement -> "image" image_name "=" python_expression

An `image` statement binds an image name to a displayable. The displayable is computed by the supplied python expression, with the result of the expression being passed to the im.Image function in loose mode. This means that if the assignment is a single string, it is interpreted as an image filename. Displayables are passed through unmolested. Once an image has been defined using an `image` statement, it can be used by the `scene`, `show`, and `hide` statements.

    init:
        image eileen happy = "eileen/happy.png"
        image eileen upset = "eileen/upset.png"

### Init Statement

The `init` statement is used to execute blocks of Ren'Py statements before the script executes. Init blocks are used to define images and characters, to set up unchanging game data structures, and to customize Ren'Py. Code inside init blocks should not interact with the user or change any of the layers, and so should not contain `say`, `menu`, `scene`, `show`, or `hide` statements, as well as calls to any function that can do these things.

    init_statement -> "init" (number)? ":"

An `init` statement is introduced with the keyword `init`, followed by an optional priority number, and a mandatory colon. If the priority is not given, it defaults to 0.

The priority number is used to determine when the code inside the init block executes. Init blocks are executed in priority order from low to high. Within a file, init blocks with the same priority are run in order from the top of the file to the bottom. The order of evaluation of priority blocks with the same priority between files is undefined.

The init blocks are all run once, during a special init phase. When control reaches the end of an init block during normal execution, execution of that block ends. If an init statement is encountered during normal execution, the init block is not run. Instead, control passes to the next statement.

### Jump Statement

The `jump` statement is used to transfer control to the statement with the given name.

    jump_statement -> "jump" name
    jump_statement -> "jump" "expression" simple_expression

If the `expression` keyword is present, the expression is evaluated, and the string so computed is used as the name of the statement to jump to. If the `expression` keyword is not present, the name of the statement to jump to must be explicitly given.

Unlike `call`, `jump` does not push the target onto any stack. As a result, there's no way to return to where you've jumped from.

    label loop_start:

    e "Oh no! It looks like we're trapped in an infinite loop."

    jump loop_start

### Label Statement

Label statements allow a name to be assigned to a program point. They exist solely to be called or jumped to, whether by script code or the Ren'Py config.

    label_statement -> "label" name ":"
    label_statement -> "label" name "(" parameters ")" ":"

A `label` statement may have a block associated with it. In that case, control enters the block whenever the label statement is reached, and proceeds with the statement after the label statement whenever the end of the block is reached.

The label statement may take an optional list of parameters. These parameters are processed as described in PEP 3102, with two exceptions:

- The values of default parameters are evaluated at call time.
- The variables are dynamically, rather than lexically, scoped.

Inside a called label, variables can be declared dynamic using the renpy.dynamic function:

Function: | renpy.dynamic | (*vars):

This declares a variable as dynamically scoped to the current Ren'Py call. The first time renpy.dynamic is called in the current call, the values of the variables named in the supplied strings are stored. When we return from the current call, the variables get their old values back. If renpy.dynamic is called twice for the same variable in a given call, it has no effect the second time.

### Menu Statement

Menus are used to present the user with a list of choices that can be made. In a visual novel, menus are the primary means by which the user can influence the story.

    menu_statement -> "menu" ( name )? ":"

A `menu` statement is introduced by the keyword `menu`, an optional name, and a colon. If the name is supplied, it is treated as a label for this `menu` statement, as if the menu statement was preceded by a label statement.

A `menu` statement must have a block associated with it. This is a menuitem block that must contain one or more menuitems in it. There are several kinds of menuitems that can be contained in a menuitem block.

    caption_menuitem -> string

The first kind of menuitem is a string. This string is placed into a menu as a caption that cannot be selected. In general, captions are used to indicate what the menu is for, especially when it is not clear from the choices.

    choice_menuitem -> string ( "if" python_expression )? ":"

The second kind of menuitem gives a choice the user can make. Each choice must have a block of Ren'Py statements associated with it. If the choice is selected by the user, then block of statements associated with the choice is executed. A choice may also have an optional `if` clause that includes a Python expression. This clause gives a condition that must be satisfied for the choice to be presented to the user. A terminating colon is used to indicate that this menuitem is a choice.

    with_menuitem -> "with" simple_expression

The final kind of menuitem is a `with` clause. Please see Transitions for more information on `with` clauses.

    menu what_to_do:

        "What should we do today?"

        "Go to the movies.":
            "We went to the movies."

        "Go shopping.":
            "We went shopping, and the girls bought swimsuits."
            $ have_swimsuits = True

        "Go to the beach." if have_swimsuits:
            "We went to the beach together. I got to see the girls in their
             new swimsuits."

#### Details

When a menu is to be shown to the user, the first thing that happens is that a list of captions and choices is built up from the menuitems associated with the menu. Each of the choices that has an expression associated with it has that expression evaluated, and if not true, that choice is removed from the list. If no choices survive this process, the menu is not displayed and execution continues with the next statement. Otherwise, the `menu` function is called with the list of choices, displays the menu to the user, and returns a chosen choice. Execution continues with the block corresponding to the chosen choice. If execution reaches the end of that block, it continues with the the statement after the menu.

### Play Statement

The play statement is used to play sound and music. If a file is currently playing, it is interrupted and replaced with the new file.

    play_statement -> "play" ( "sound" | "music" ) simple_expression
                           ( "fadeout" simple_expression )?
                           ( "fadein" simple_expression )?
                           ( "channel" simple_expression )?

The first simple_expression in the play statement is expected to evaluate to either a string containing a filename, or a list of filenames to be played. The file is played using renpy.sound.play or renpy.music.play}, depending on the second keyword in the statement. The other clauses are all optional. Fadeout and fadein expect times in seconds, while channel expects a channel number. The channel number defaults to 0 for sound and 7 for music.

    play music "mozart.ogg"
    play sound "woof.ogg"

    "Let's try something more complicated."

    play music [ "a.ogg", "b.ogg" ] fadeout 1.0 fadein 1.0

### Pass Statement

The `pass` statement does not perform an action. It exists because blocks of Ren'Py statements require at least one statement in them, and it's not always sensible to perform an action in those blocks.

    pass_statement -> "pass"

    menu:
        "Should I go to the movies?"

        "Yes":
            call go_see_movie

        "No":
            pass

    "Now it's getting close to dinner time, and I'm starving."

### Python Statement

The `python` statement allows one to execute Python code in a Ren'Py script. This allows one to use Python code to declare things to Ren'Py, to invoke much of Ren'Py's functionality, and to store data in variables that can be accessed by user code. There are two forms of the `python` statement:

    python_statement -> "$" python_code
    python_statement -> "python" ( "hide" )? ":"

The first form of a python consists of a dollar sign (`$`) followed by Python code extending to the end of the line. This form is used to execute a single Python statement.

A second form consists of the keyword `python`, optionally the keyword `hide`, and a colon. This is used to execute a block of Python code, supplied after the statement. Normally, Python code executes in a script-global namespace, but if the `hide` keyword is given, a new namespace is created for this block. (The script-global namespace can be accessed from the block, but not assigned to.)

    $ score += 1

    python:
        ui.text("This is text on the screen.")
        ui.saybehavior()
        ui.interact()

Init Python Statement. For convenience, we have created the init pythons statement. This statement combines an init statement and a python statement into a single statement, to reduce the indentation required for python-heavy files.

    init python_statement -> "init" ( number )? "python" ( "hide" )? ":"

### Queue Statement

The queue statement is used to queue up sound and music files. They will be played when the current track finishes playing.

    queue_statement -> "queue" ( "sound" | "music" ) simple_expression
                           ( "channel" simple_expression )?

The first simple_expression in the queue statement is expected to evaluate to either a string containing a filename, or a list of filenames to be queued up. The files are queued using renpy.sound.queue or renpy.music.queue}, depending on the second keyword in the statement. The channel number defaults to 0 for sound and 7 for music, if not given.

    queue sound "woof.ogg"
    queue music [ "a.ogg", "b.ogg" ]

### Return Statement

The `return` statement pops the top location off of the call stack, and transfers control to it. If the call stack is empty, the return statement performs a full restart of Ren'Py.

    return_statement -> "return"
    return_statement -> "return" expression

If the optional expression is given to return, it is evaluated, and it's result is stored in the _return variable. This variable is dynamically scoped to each context.

### Say Statement

The say statement is used to present text to the user, in the form of dialogue or thoughts. Since the bulk of the of the content of a script will be dialogue or thoughts, it's important that the say statement be as convenient as possible. Because of this, the say statement is the only statement that is not delimited with a keyword or other form of delimiter. Instead, it consists of a string, with an optional simple_expression before it to designate who is doing the speaking, and an optional `with` clause after it used to specify a transition.

    say_statement -> ( simple_expression )? string ( "with" simple_expression )?

There are two forms of the say statement, depending on if the simple expression is provided. The single-argument form consists of a single string (with or without the optional with clause). This form causes the string to be displayed to the user as without any label as to who is saying it. Conventionally, this is used to indicate POV character thoughts or narration.

    "I moved to my left, and she moved to her right."

    "So we were still blocking each other's path."

    "I then moved to my right, and at the same time she moved to her
     left."

    "We could be at this all day."

The two-argument form of the say statement consist of a simple_expression, a string, and optionally a `with` clause. This form of the statement is used to indicate dialogue. The first argument is expected to be an object (usually a Character or DynamicCharacter object) that knows how to show dialogue to the user. The string is then passed to that object, which is responsible for showing it to to the user.

The simple_expression can also be a string, rather than an object. Strings are used directly as the name of the character.

    "Girl" "Hi, my name is Eileen."

    e "Starting today, I'll be living here."

#### Details

The two-argument say statement first evaluates the supplied simple expression. It then attempts to call that value (the who value) with the string giving the line of dialogue (the what string). If it can do so, it's finished, as the object that is called is responsible for interacting with the user.

If it can't call the value of the expression, then it copies the `name_only` character object, supplying the given string as a new character name, and then uses that to say the dialogue. (This is done by the `say` and `predict_say` functions found in the store. Changing these functions can change this behavior.)

The single-argument form of the statement simply calls the special function (or object) `narrator` with the string to be shown. This function is responsible for showing the string to the user. Character and DynamicCharacter objects are suitable for use as the `narrator`.

The `with` clause is used to specify a transition, see With Statement and Clauses for details.

### Scene Statement

The `scene` statement clears a layer by removing all images from it. It may then show a supplied image to the user. This makes it appropriate for changing the background of a scene.

    scene_statement -> "scene" ("onlayer" name | image_spec )?

The scene statement first clears out all images from a layer. The layer is taken from the image_spec or `onlayer` clause, if present. The "master" layer is used if no other layer is specified.

If an image_spec is present, it is then added to the layer, as with the `show` statement.

By default, no background is added to the screen, so we recommend that every script begin with a scene statement that shows a full-screen background to the user.

### Show Statement

The `show` statement takes an image specifier, and adds the specified image to the specified layer, with the "master" layer used if no `onlayer` clause is present.

    show_statement -> "show" image_spec

The `show` statement first finds a displayable to add to the screen. This is done by looking up the image name in the list of registered images. It then applies all transformations into the at list to the displayable. This yields the image to be added to the layer. The show statement then checks to see if an image beginning with the same image tag can be found in the layer. If such an image exists, it is replaces with the new image. Otherwise, the new image is added to the layer, in a position that makes it closer to the user than any other image.

    scene living_room
    show eileen happy at left

    e "I'm feeling happy right now."

    show eileen upset at left

    e "But sometimes, I can get upset for no good reason."

### Stop Statement

The stop statement is used to stop playing sound and music.

    stop_statement -> "stop" ( "sound" | "music" )
                           ( "fadeout" simple_expression )?
                           ( "channel" simple_expression )?

The sound or music is stopped using renpy.sound.stop or renpy.music.stop}, depending on the second keyword in the statement. The other clauses are all optional. Fadeout expects a time in seconds, while channel expects a channel number. The channel number defaults to 0 for sound and 7 for music.

    stop sound
    stop music fadeout 1.0

### With Statement and Clauses

The `with` statement and `with` clauses are used to show transitions to the user. These transitions are always from the last screen shown to the user to the current screen. At the end of a `with` statement, the last screen shown to the user is set to the current screen. The last screen shown to the user can also be updated by `say` or `menu` statements, as well as by Python code.

The `with` statement has the form:

    with_statement -> "with" simple_expression

The simple_expression is expected to evaluate to a transition function. If it evaluates to the value None, the last screen shown to the user is updated to the current screen, without performing a transition. This is useful to remove transient interface items (like a prior `say` statement) from partaking in a transition.

For convenience, a number of statements support `with` clauses. In the case of the `scene`, `show`, and `hide` statements, the `with` clause is equivalent to placing a "with None" statement before the `scene`, `show` or `hide` statement, and a "with transition" statement after it. For example, the statement:

    show eileen happy with dissolve

is equivalent to:

    with None
    show eileen happy
    with dissolve

This behavior can lead to undesired side-effects. The code:

    show bg whitehouse with dissolve
    show eileen happy with dissolve

will cause two transitions to occur. To ensure only a single transition occurs, one must write:

    with None
    show bg whitehouse
    show eileen happy
    with dissolve

With clauses can also be applied to `say` and `menu` statements. In this case, the transition occurs when the dialogue or menu is first shown to the user.

For pre-defined transition functions that can be used in any script, see Pre-defined Transitions. For functions that return transition functions, see Transition Constructors.

### While Statement

The `while` statement is used to execute a block of Ren'Py statement while a condition remains true.

    while_statement -> "while" python_expression ":"

When a `while` statement is executed, the python_expression is evaluated. If it evaluates to true, control is transferred to the first statement in the block associated with this `while` statement. If false, control is instead sent to the statement following the `while` statement.

When control reaches the end of the block associated with the while statement, it returns to the `while` statement. This allows the `while` statement to check the condition again, and evaluate the block if the condition remains true.

    while not endgame:

       "It's now morning. Time to get up and seize the day."

        call morning
        call afternoon
        call evening

        "Well, time to call it a night."

    "Now it's time to wake up and face the endgame."

documentation index ◦ reference manual ◦ function index