Skip to reading
GDScript Programming & Godot

9. Match and named states

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func describe_lock(state: String) -> String:
    match state:
        "locked":
            return "I need a key."
        "open", "unlatched":
            return "The way is clear."
        _:
            return "The mechanism is damaged."
Code example
func run() -> String:
    return describe_lock("open")

match compares a value with patterns. The underscore is the fallback. Comma-separated patterns share a response. A matched branch does not fall through into the next branch.

Use match for a clearly defined state or command type. Use if/elif when your tests are separate conditions such as inventory possession, a room visit and a distance measurement.

Page 17 of 378Permalink
Go to page