Skip to content

Instantly share code, notes, and snippets.

@Timofffee
Last active April 20, 2018 22:08
Show Gist options
  • Save Timofffee/fef6ad90564c36c380fd3579a75917b9 to your computer and use it in GitHub Desktop.
Save Timofffee/fef6ad90564c36c380fd3579a75917b9 to your computer and use it in GitHub Desktop.

Language

Keywords

if          # See "if/else/elif".
elif        # See "if/else/elif".
else        # See "if/else/elif".
for         # See "for".
do          # Reserved for future implementation of do…while loops.
while       # See "while".
match       # See "match".
switch      # Reserved for future implementation.
case        # Reserved for future implementation.
break       # Exits the execution of the current `for` or `while` loop.
continue    # Immediately skips to the next iteration of the `for` or `while` loop.
pass        # Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions.
return      # Returns a value from a function.
class       # Defines a class.
extends     # Defines what class to extend with the current class.
is          # Tests whether a variable extends a given class.
tool        # Executes the script in the editor.
signal      # Defines a signal.
func        # Defines a function.
static      # Defines a static function. Static member variables are not allowed.
const       # Defines a constant.
enum        # Defines an enum.
var         # Defines a variable.
onready     # Initializes a variable once the Node the script is attached to and its children are part of the scene tree.
export      # Saves a variable along with the resource it’s attached to and makes it visible and modifiable in the editor.
setget      # Defines setter and getter functions for a variable.
breakpoint  # Editor helper for debugger breakpoints.

Operators

x[index]                # Subscription, Highest Priority
x.attribute             # Attribute Reference
is                      # Instance Type Checker
~                       # Bitwise NOT
-x                      # Negative
* / %                   # Multiplication / Division / Remainder
+ -                     # Addition / Subtraction
<< >>                   # Bit Shifting
&                       # Bitwise AND
^                       # Bitwise XOR
|                       # Bitwise OR
< > == != >= <=         # Comparisons
in                      # Content Test
! not                   # Boolean NOT
and &&                  # Boolean AND
or ||                   # Boolean OR
if x else               # Ternary if/else
= += -= *= /= %= &= |=  # Assignment, Lowest Priority

Literals

45                      # Base 10 integer
0x8F51                  # Base 16 (hex) integer
3.14, 58.1e-10          # Floating point number (real)
"Hello", 'Hi'           # Strings
"""Hello, Dude"""       # Multiline string
@"Node/Label"           # NodePath or StringName

Comments

# This is a comment

Built-in types

Basic built-in types

null    # empty data type
bool    # can only contain `true` or `false`
int     # can only contain integer numbers, (both negative and positive)
float   # used to contain a floating point value
String  # a sequence of characters in Unicode format

Vector built-in types

Vector2     # 2D vector type containing `x` and `y` fields. 
Rect2       # 2D Rectangle type containing two vectors fields: `position` and `size`
            # Alternatively contains an `end` field which is `position+size`
Vector3     # 3D vector type containing x, y and z fields
Transform2D # 3x2 matrix used for 2D transforms
Plane       # 3D Plane type in normalized form that contains 
            # a normal vector field and a d scalar distance
Quat        # Quaternion is a datatype used for representing a 3D rotation
AABB        # Axis-aligned bounding box (or 3D box) contains 2 vectors fields: `position` and `size`
            # Alternatively contains an `end` field which is `position+size`
Basis       # 3x3 matrix used for 3D rotation and scale

Engine built-in types

Color       # Color data type contains r,g,b,a or h,s,v fields or HEX code.
NodePath    # Compiled path to a node used mainly in the scene system
RID         # Resource ID (RID)
Object      # Base class for anything that is not a built-in type

Container built-in types

Arrays

var arr = []
arr = [1, 2, 3]
var b = arr[1]              # this is 2
var c = arr[arr.size() - 1] # this is 3
var d = arr[-1]             # same as the previous line, but shorter
arr[0] = "Hi!"              # replacing value 1 with "Hi"
arr.append(4)               # array is now ["Hi", 2, 3, 4]
Array Types
PoolByteArray()     # An array of bytes (integers from 0 to 255).
PoolIntArray()      # An array of integers.
PoolRealArray()     # An array of floats.
PoolStringArray()   # An array of strings.
PoolVector2Array()  # An array of Vector2 objects.
PoolVector3Array()  # An array of Vector3 objects.
PoolColorArray()    # An array of Color objects.

Dictionary

var d = {4: 5, "a key": "a value", 28: [1, 2, 3]}
d["Hi!"] = 0
d = {
    22: "Value",
    "somekey": 2,
    "otherkey": [2, 3, 4],
    "morekey": "Hello"
}
Lua style
var d = {
    test22 = "Value",
    somekey = 2,
    otherkey = [2, 3, 4],
    morekey = "Hello"
}
Add key
var d = {}        # create an empty Dictionary
d.waiting = 14    # add String "Waiting" as a key and assign the value 14 to it
d[4] = "hello"    # add integer `4` as a key and assign the String "hello" as its value
d["Godot"] = 3.01 # add String "Godot" as a key and assign the value 3.01 to it

# (4:hello), (Godot:3.01), (waiting:14)

Data

Variables

var a          # data type is null by default
var b = 5
var c = 3.8
var d = b + c  # variables are always initialized in order

Constants

const a = 5
const b = Vector2(20, 20)
const c = 10 + 20            # constant expression
const d = Vector2(20, 30).x  # constant expression: 20
const e = [1, 2, 3, 4][0]    # constant expression: 1
const f = sin(20)            # sin() can be used in constant expressions
const g = x + 20             # invalid; this is not a constant expression!

Enums

enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
# Is the same as:
const TILE_BRICK = 0
const TILE_FLOOR = 1
const TILE_SPIKE = 2
const TILE_TELEPORT = 3

enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
# Is the same as:
const STATE_IDLE = 0
const STATE_JUMP = 5
const STATE_SHOOT = 6
const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}

Functions

func myfunction(a, b):
    print(a)
    print(b)
    # return is optional; without it null is returned
    return a + b  

Referencing Functions

# To call a function in a base class, prepend . to the function name:
.basefunc(args)

Static functions

static func sum2(a, b):
    return a + b

Statements and control flow

if/else/elif

if [expression]:
    statement(s)
elif [expression]:
    statement(s)
else:
    statement(s)

# short
if 1 + 1 == 2: return 2 + 2
else:
    var x = 3 + 3
    return x

# very short
var x = [true-value] if [expression] else [false-value]
y += 3 if y < 10 else -1

while

while [expression]:
    statement(s)

for

for x in [5, 7, 11]:
    statement # loop iterates 3 times with x as 5, then 7 and finally 11

var dict = {"a": 0, "b": 1, "c": 2}
for i in dict:
    print(dict[i])

for i in range(3):
    statement # similar to [0, 1, 2] but does not allocate an array

for i in range(1,3):
    statement # similar to [1, 2] but does not allocate an array

for i in range(2,8,2):
    statement # similar to [2, 4, 6] but does not allocate an array

for c in "Hello":
    print(c) # iterate through all characters in a String, print every letter on new line

match

match [expression]:
    [pattern](s):
        [block]
    [pattern](s):
        [block]
    [pattern](s):
        [block]
  • constant pattern
match x:
    1:
        print("We are number one!")
    2:
        print("Two are better than one!")
    "test":
        print("Oh snap! It's a string!")
  • variable pattern
match typeof(x):
    TYPE_FLOAT:
        print("float")
    TYPE_STRING:
        print("text")
    TYPE_ARRAY:
        print("array")
  • wildcard pattern
match x:
    1:
        print("it's one!")
    2:
        print("it's one times two!")
    _:
        print("it's not 1 or 2. I don't care tbh.")
  • binding
match x:
    1:
        print("it's one!")
    2:
        print("it's one times two!")
    var new_var:
        print("it's not 1 or 2, it's ", new_var)
  • array pattern
match x:
    []:
        print("empty array")
    [1, 3, "test", null]:
        print("very specific array")
    [var start, _, "test"]:
        print("first element is ", start, ", and the last is \"test\"")
    [42, ..]:
        print("open ended array")
  • dictionary pattern
match x:
    {}:
        print("empty dict")
    {"name": "dennis"}:
        print("the name is dennis")
    {"name": "dennis", "age": var age}:
        print("dennis is ", age, " years old.")
    {"name", "age"}:
        print("has a name and an age, but it's not dennis :(")
    {"key": "godotisawesome", ..}:
        print("I only checked for one entry and ignored the rest")
  • Multipatterns
match x:
    1, 2, 3:
        print("it's 1 - 3")
    "sword", "splashpotion", "fist":
        print("yep, you've taken damage")

Classes

Inheritance

# Inherit/extend a globally available class
extends SomeClass

# Inherit/extend a named class file
extends "somefile.gd"

# Inherit/extend an inner class in another file
extends "somefile.gd".SomeInnerClass
Check
# Cache the enemy class
const enemy_class = preload("enemy.gd")

# [...]

# use 'is' to check inheritance
if (entity is enemy_class):
    entity.apply_damage()

Class Constructor

func _init(args).(parent_args):
   pass

Inner classes

# Inside a class file

# An inner class in this class file
class SomeInnerClass:
    var a = 5
    func print_value_of_a():
        print(a)

# This is the constructor of the class file's main class
func _init():
    var c = SomeInnerClass.new()
    c.print_value_of_a()

Classes as resources

# Load the class resource when calling load()
var MyClass = load("myclass.gd")

# Preload the class only once at compile time
var MyClass2 = preload("myclass.gd")

func _init():
    var a = MyClass.new()
    a.somefunction()

Exports

# If the exported value assigns a constant or constant expression,
# the type will be inferred and used in the editor

export var number = 5

# Export can take a basic data type as an argument which will be
# used in the editor

export(int) var number

# Export can also take a resource type to use as a hint

export(Texture) var character_face
export(PackedScene) var scene_file

# Integers and strings hint enumerated values

# Editor will enumerate as 0, 1 and 2
export(int, "Warrior", "Magician", "Thief") var character_class
# Editor will enumerate with string names
export(String, "Rebecca", "Mary", "Leah") var character_name

# Strings as paths

# String is a path to a file
export(String, FILE) var f
# String is a path to a directory
export(String, DIR) var f
# String is a path to a file, custom filter provided as hint
export(String, FILE, "*.txt") var f

# Using paths in the global filesystem is also possible,
# but only in tool scripts (see further below)

# String is a path to a PNG file in the global filesystem
export(String, FILE, GLOBAL, "*.png") var tool_image
# String is a path to a directory in the global filesystem
export(String, DIR, GLOBAL) var tool_dir

# The MULTILINE setting tells the editor to show a large input
# field for editing over multiple lines
export(String, MULTILINE) var text

# Limiting editor input ranges

# Allow integer values from 0 to 20
export(int, 20) var i
# Allow integer values from -10 to 20
export(int, -10, 20) var j
# Allow floats from -10 to 20, with a step of 0.2
export(float, -10, 20, 0.2) var k
# Allow values y = exp(x) where y varies between 100 and 1000
# while snapping to steps of 20. The editor will present a
# slider for easily editing the value.
export(float, EXP, 100, 1000, 20) var l

# Floats with easing hint

# Display a visual representation of the ease() function
# when editing
export(float, EASE) var transition_speed

# Colors

# Color given as Red-Green-Blue value
export(Color, RGB) var col # Color is RGB
# Color given as Red-Green-Blue-Alpha value
export(Color, RGBA) var col # Color is RGBA

# Another node in the scene can be exported too

export(NodePath) var node

# Exporting bit flags

# Individually edit the bits of an integer
export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER
# Set any of the given flags from the editor
export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0

# Exported array, shared between all instances.
# Default value must be a constant expression.

export var a=[1,2,3]

# Typed arrays also work, only initialized empty:

export var vector3s = PoolVector3Array()
export var strings = PoolStringArray()

# Regular array, created local for every instance.
# Default value can include run-time values, but can't
# be exported.

var b = [a,2,3]

Setters/getters

var myvar setget myvar_set,myvar_get

func myvar_set(newvalue):
    myvar=newvalue

func myvar_get():
    return myvar # getter must return a value

Tool mode

# Must restart Godot
tool
extends Button

func _ready():
    print("Hello")

Signals

# No arguments
signal your_signal_name
# With arguments
signal your_signal_name_with_args(a,b)

func _callback_no_args():
    print("Got callback!")

func _callback_args(a,b):
    print("Got callback with args! a: ", a, " and b: ", b)

func _at_some_func():
    instance.connect("your_signal_name", self, "_callback_no_args")
    instance.connect("your_signal_name", self, "_callback_args", [22, "hello"])
    instance.connect("your_signal_name_with_args", self, "_callback_args")

func _second_at_some_func():
    emit_signal("your_signal_name")
    emit_signal("your_signal_name_with_args", 55, 128)
    someinstance.emit_signal("somesignal")

Coroutines

func myfunc():
   print("hello")
   yield()
   print("world")

func _ready():
    var y = myfunc()
    # Function state saved in 'y'
    print("my dear")
    y.resume()
    # 'y' resumed and is now an invalid state

#> hello
#> my dear
#> world
func myfunc():
   print("hello")
   print(yield())
   return "cheers!"

func _ready():
    var y = myfunc()
    # Function state saved in 'y'
    print(y.resume("world"))
    # 'y' resumed and is now an invalid state

#> hello
#> world
#> cheers!

Coroutines & signals

# Resume execution the next frame
yield(get_tree(), "idle_frame")

# Resume execution when animation is done playing:
yield(get_node("AnimationPlayer"), "finished")

# Wait 5 seconds, then resume execution
yield(get_tree().create_timer(5.0), "timeout")

Onready keyword

var mylabel

func _ready():
    mylabel = get_node("MyLabel")

# Is the same as:

onready var mylabel = get_node("MyLabel")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment