Gama
Gama is Gamma's own scripting language, in .gma files. It reads like Luau, drops the parts of Luau that trip people up, and adds what Gamma programs do all the time: connecting events, scheduling work, building UI and instance trees, and writing vectors and colours.
Gama ships inside Gamma. You don't install anything: a .gma file runs wherever a .luau file does. When Gamma loads a .gma file it translates it to Luau in memory and runs it on the Luau VM.
let Crates = require("./src/Crates")
const Speed = 2
Surface {
Target = "Window",
Padding = 20,
Parent = Scene,
Text { Text = "Hello from Gama", FontSize = 28, Color = $ffffff },
}
on Run.Heartbeat(deltaTime)
Crates.Spin(deltaTime * Speed)
end
every 1 do
print("tick")
endNew to Gama? Your first game in Gama builds a small physics game step by step. Short on time? Skip to the cheat sheet.
How it runs
Gamma run file.gmaandGamma play file.gmarun a Gama file. A project folder can have amain.gmainstead of amain.luau, but not both (see projects.md).requirefindsx.gmaandx/init.gmathe way it findsx.luauandx/init.luau. Gama and Luau modules can require each other. Having bothx.gmaandx.luaumakesrequire("./x")ambiguous, which is an error.- The translation keeps every line on the line it came from, so the line numbers in errors and tracebacks point into the
.gmafile. A Gama error, such as a~=, stops the file from loading and is reported asfile.gma:line: message. .luaurcaliases, the sandbox, the services and every engine type work just as they do in Luau.
What Gama keeps from Luau
Expressions, operators, tables, strings (including interpolated strings in backticks), numbers, if expressions, for, while, repeat, continue, compound assignment (+= and the rest), type annotations, type aliases, generics, typeof, :: casts, -- comments and attributes such as @native. The standard libraries (math, string, table, task and the rest) are the same.
What Gama changes
| Gama | Instead of Luau's | Notes |
|---|---|---|
let x = 1 | local x = 1 | local is an error |
const X = 1 | local X = 1 | Assigning to a const again, += included, is an error, and so is a const without a value. Only the name is constant: const T = {} can still change T.x. Use table.freeze to make a table read only |
fn name(a) ... end | local function name(a) ... end | A named function is local. fn T.name() and fn T:name() define a field or method of T, which must already be declared. fn(a) ... end is an anonymous function. function is an error |
for i in 1..10 do | for i = 1, 10 do | a..b counts from a to b, and a..<b stops before b (for whole numbers, as it counts to b - 1). Either can end with by step, such as for i in 10..1 by -1. Outside a for ... in, or in brackets, .. still joins strings. The start of a range stops at .., so a comparison in it needs parentheses |
fn f(a: number = 1) | local function f(a: number?) local a: number = if a == nil then 1 else a | A parameter's default value is used when the argument is nil or left out. Its type becomes optional for callers, and a literal default gives an untyped parameter its type. The value must be on the parameter's line |
let { x, y } = point | local x, y = point.x, point.y | Takes fields by name. let [a, b] = list takes list[1] and list[2]. The value runs once, and const works the same way. A for loop's variables can be patterns too: for { x, y } in points do takes the fields of each value, and for i, [a, b] in ipairs(pairs) do the items. A pattern on its own takes each value, as for _, item in would |
fn(x) => x * 2 | function(x) return x * 2 end | A function whose body is one expression, which it returns, needs no end. Named functions and on handlers can use it too |
enum Mode { Fast, Slow } | local Mode = table.freeze({ Fast = "Fast", Slow = "Slow" }) and type Mode = "Fast" | "Slow" | Each item is the string of its own name, typed as that string, so let m: Mode = Mode.Fast type checks and "Fats" does not. The table cannot be changed. export enum exports both. enum is not a keyword |
a != b | a ~= b | ~= is an error |
| No implicit globals | x = 1 makes a global | Assigning to a name that was never declared is an error. Declare it with let |
export let, export const, export fn | return { ... } at the end | See Modules |
let, const, fn, on, once, after, every, spawn, wait, asset and continue are keywords, so they cannot name variables. They can still be field names (signal.once) and table keys ({ on = true }).
Nil
| Gama | Does |
|---|---|
a ?? b | a, or b when a is nil. false ?? b is false. b runs only when it is needed. ?? binds more loosely than or and groups from the right |
a ??= b | Sets a to b when a is nil. The left side must be a name or a .field path |
a?.b, a?[k], a?:m() | nil when a is nil, and otherwise a.b, a[k] or a:m(). Once a is nil the rest of the chain does not run, so a?.b.c is nil rather than an error |
let volume = settings.volume ?? 1
player?.Character?.Humanoid:TakeDamage(10)
cache[key] = cache[key] ?? load(key)Each side runs once. a ?? b and a chain with one ?. after a name or a .field path become a Luau if expression; anything else, such as f() ?? b, keeps the value in a local of a function that is called at once, which costs a closure each time it runs.
Pipes
a |> f(b) calls f(a, b): the value on the left becomes the first argument of the call on the right. A chain reads in the order it runs, and each step can go on a line of its own:
let label = players
|> countAlive()
|> math.min(99)
|> tostring()
health |> math.clamp(0, 100)
parts |> table.sortThe right side is a function, a .field of one or a :method(...) call, written on the |>'s line, with or without arguments: x |> print is print(x), and s |> s:rep(2) is s:rep(s, 2). |> binds more loosely than every other operator, so a + 1 |> f passes a + 1, and a chain groups from the left. A pipeline can also be a statement on its own.
Match
match compares one value with the values after each when, in order, and runs the block of the first that is equal (==). A when can list several values, separated by commas. else runs when none is equal. The value runs once.
match input.KeyCode
when Enum.KeyCode.W, Enum.KeyCode.Up then
move(1)
when Enum.KeyCode.S then
move(-1)
else
stop()
endmatch is also an expression, whose whens and else each give one value. Without an else, it is nil when nothing matches:
let label = match count
when 0 then "none"
when 1 then "one"
else `{count}`
endA when can also test more than equality:
| Pattern | Matches |
|---|---|
when 1..5, when 0..<10 | A number in the range, from the first to the last, or stopping before it with ..<. Ranges and values mix: when 1..5, 10 |
when { kind = "hit", damage } | A table whose kind field equals "hit" and whose damage field is not nil. A bare name, such as damage, also names that field's value in the case's block. when {} matches any table |
when let n | Anything, and names it n in the case's block |
... if condition | After any of the above: the case also needs the condition, which can use the names the pattern gives. when 1, 2 if ready |
match event
when { kind = "hit", damage } if damage > 50 then
flash(Color.Red)
health -= damage
when { kind = "hit", damage } then
health -= damage
when { kind = "heal", amount } then
health = math.min(health + amount, 100)
endThe names a when gives belong to it alone: another when, the else and the code after end cannot see them. In a match expression they work the same way.
Writing the same literal after two whens is an error. When the value is typed as an enum and every when lists plain values, Gamma check and the language server warn about a match without an else that leaves out some of the enum's items, and name them. match and when are not keywords: they start a match only at the start of a statement and followed by a value on the same line, so match and when still work as names, and match(x) is still a call.
Classes
class Counter
count: number = 0
history: { number } = {}
label = "counter"
fn new(label: string = "clicks")
self.label = label
end
fn Increment(by: number = 1): number
self.count += by
table.insert(self.history, self.count)
return self.count
end
end
let clicks = Counter.new()
clicks:Increment()A class has fields, methods and at most one constructor, in any order, and ends with end. It becomes Luau's metatable idiom: Counter is a table that is its own __index, Counter is also the type of its instances, and every method is a function of Counter that takes self typed as Counter, so clicks:Increment() type checks and clicks:Nope() is an error.
- A field is
name: type = value. Either the type or the value can be left out. A field without a type takes its value's type, except{}, which isany. Each instance gets the value anew, sohistoryabove is a table of its own for each counter. A value must fit on one line. Counter.new(...)makes an instance. It sets every field with a value, then runs the constructor,fn new, withselfas the new instance, and returns it. Without a constructor,Counter.new()takes no arguments.- Methods are called with
:, as in Luau.
class is not a keyword: class Name starts a class only when its body starts on the next line. export class exports the table and the type.
Static members and getters
class Rect
static made = 0
w = 1
h = 1
static fn square(size: number): Rect
Rect.made += 1
let rect = Rect.new()
rect.w = size
rect.h = size
return rect
end
get area(): number => self.w * self.h
end
let tile = Rect.square(3)
print(tile.area, Rect.made) -- 9 1static name = valuesets a field on the class itself, once, rather than on each instance, so it is shared: read and change it asRect.made. It needs a value. Instances can read it too, but assigningself.madegives that instance a field of its own.static fnmakes a function of the class that takes noself, called asRect.square(3). The constructor cannot be static.get name(): typemakes a property that runs its body each time it is read, withselfas the instance, sotile.areachanges whentile.wdoes. A getter takes no parameters, and its return type becomes the property's type. Assigning to it gives the instance a field that hides the getter.- A subclass keeps its parent's getters and static members and can add its own. A class with getters looks members up through a function rather than a table, which is a little slower.
static and get only mean this before a member's name, so fields can still be called static or get.
Extending a class
class Dog extends Animal
tricks = 0
fn new(name: string)
super(name)
self.tricks = 1
end
fn Speak(): string
return super:Speak() .. ", woof"
end
endclass Dog extends Animal makes a class whose instances are Animals too: they have its fields and methods, a Dog can be passed where an Animal is expected, and a method of the same name replaces the parent's. The parent is a class declared earlier, or a path to one, such as Shapes.Animal from a module.
- In the constructor,
super(...)calls the parent's constructor, which makes the instance, then sets the subclass's own fields. Call it before anything usesself. A constructor without it starts fromAnimal.new()with no arguments. super:Method(...)calls the parent's method onself, andsuper.namereads the parent class's field.- Without a constructor,
Dog.new(...)passes its arguments on to the parent's constructor, so they are not type checked.
Defer
defer followed by a statement saves the statement to run when the fn it is in ends, whether the function returns or raises an error. Deferred statements run last first, so things are closed in the opposite order to how they were opened. After them, the function returns its values, or the error goes on to the caller.
let loading = 0
fn load(name: string): string
loading += 1
defer loading -= 1
if name == "" then
error("no name")
end
return `loaded {name}`
enddeferworks directly in afnor anonhandler, not in anafter,everyorspawnbody, nor at the top of a file.- The statement can be a block:
defer do ... end. It cannot use..., so put the values in aletfirst. - The values the statement uses are read when it runs, not when
deferis reached, as in a closure. - A function with a
deferruns its body in apcall, so an error raised from it is raised again with level 0: its message keeps the place it came from, and the stack trace starts at the function. An error in a deferred statement skips the ones that would run after it. deferis a keyword only at the start of a statement, so a variable can still be nameddefer.
Try
try runs a block and catches an error raised in it. catch names the error and runs when there was one; finally runs afterwards however the rest ended, by finishing, returning or raising an error. A try needs a catch, a finally or both, and ends with end.
fn loadSave(name: string): Save?
try
return Saves.Read(name)
catch err
warn(`could not read {name}: {err}`)
return nil
finally
spinner.Visible = false
end
end- An error in the
catchblock still runsfinally, and then goes on to the caller, as does an error with nocatch. catchon its own, without a name, catches the error without keeping it.- A
returnin the body or thecatchreturns from thefnthetryis in, afterfinallyhas run. breakandcontinuecannot leave atry, since its body runs in a function of its own: set a variable, andbreakafterend. Loops inside thetrycan use them. The body cannot use...either, so put the values in aletfirst.try,catchandfinallyare keywords only alone at the start of a line (catchmay have the error's name after it), so variables can still have these names.
Modules
A module declares what it gives other files with export. Gama returns those names as a table at the end of the file:
-- Shapes.gma
const Corners = { triangle = 3, square = 4 }
export const Default = "triangle"
export fn Sides(shape: string): number
return Corners[shape]
endlet Shapes = require("./Shapes")
print(Shapes.Sides(Shapes.Default))export { Sides, Default } from "./Shapes" passes on names another module exports, as if this module had declared them, so a folder can have one module that gathers what the others give.
Only top-level declarations can be exported. A module that exports names cannot also return at its top level. A module without exports returns whatever it returns, as in Luau. export type exports a type, as in Luau.
Events
on connects a function to a signal and gives back the Connection. once connects it for the next firing only.
on Run.Heartbeat(deltaTime)
spinner.Transform *= Transform.Angles(0, deltaTime, 0)
end
let connection = on Input.InputBegan(input)
print(input.KeyCode)
end
connection:Disconnect()
once Run.Heartbeat do
print("first frame")
end
on part:GetPropertyChangedSignal("Size")()
print("resized")
endThe signal is a name followed by .field, [key] or :method(arguments) parts. Then come the handler's parameters in parentheses, or do when it takes none. The body ends with end.
Keys
on key runs the body when one of the keys after it is pressed, and on keyup when one is let go. The names are Enum.KeyCode items, and a press that a text box or another UI node took is skipped, as it is when InputBegan's second argument is true.
on key Space, W do
jump()
end
let pause = on keyup Escape do
menu.Visible = not menu.Visible
endIt gives back the Connection, like any on. once key is an error, since the first key of any kind would use it up. key and keyup only mean this between on and a key's name, so on key.Changed(value) still connects to a signal named key.
Scheduling
| Gama | Does |
|---|---|
after 2 do ... end | Runs the body once after 2 seconds, as task.delay does, and gives back its thread |
every 0.5 do ... end | Runs the body over and over, waiting 0.5 seconds before each run, in a thread of its own that it gives back. break in the body stops it, and so does task.cancel(thread) |
spawn do ... end | Runs the body at once in a new thread, as task.spawn does |
every 0.5 now do ... end | The same, but runs the body once before the first wait |
wait until ready | Yields one step at a time until ready is true, checking it first. It is a statement, and until must be on wait's line, since a bare wait can end a repeat body |
wait 1 | Yields for 1 second and gives back the time waited, as task.wait(1) does. wait on its own waits one step |
let ticker = every 1 do
seconds += 1
clock.Text = `{seconds} s`
end
after 10 do
task.cancel(ticker)
endafter, every and spawn are expressions as well as statements, and so is wait: let elapsed = wait 0.1.
Trees
A UI node or creatable class name followed directly by a table builds that node or instance. Keyed entries set properties, connect functions to events of the same name, or set Parent, which is set last. Entries without a key are children, in order:
let hud = View {
Gap = 8,
Padding = "8px 14px",
Text { Text = "Score", FontSize = 18 },
View {
Background = $6d8dff,
Text { Text = "Restart" },
Click = fn()
restart()
end,
},
}
let crate = Model {
Name = "Crate",
Parent = Scene,
Part { Size = <2, 2, 2>, Anchored = true },
}A string between the class and the brace names the instance, so Part "Floor" { ... } is Part { Name = "Floor", ... }. The string, the name and the brace must be on one line.
Model "Crate" {
Parent = Scene,
Part "Lid" { Size = <2, 0.2, 2> },
}Each child is cast to Instance for the type checker, so children of different classes, or a child held in a variable, can share one table.
UI nodes (View, ScrollView, Text, TextInput, Terminal, Image and Surface) build through Ui.View and the other constructors. Other classes build through Ui.new, and the result is typed as that class, so crate above is a Model. A local variable of the same name wins: if View is a local, View { ... } calls it, as Luau would. See ui.md for the props.
Gamma check and the language server check each key against the class: a key that is neither a property nor an event, such as Sise, is an error that names the closest one, and so is a method, a value of the wrong type (Anchored = 1, or Position = <1, 2> for a Vector3), a non-function for an event, and a string that is not an item of an enum property (Material = "Neonn"). A value bound to a Ui.State or Ui.Computed is left to the state. In an editor, the keys a tree does not set yet are offered first, with their types, and hovering a key shows its type.
Debugging
dbg(value) prints the file, the line, the source of each argument and its value, then gives back the values, so it can wrap any expression without changing what it does:
let speed = dbg(base * boost) + 1 -- main.gma:4: base * boost = 6
dbg(player.Name, health) -- main.gma:5: player.Name = Ada health = 80Each argument is one value. dbg is not a keyword: a variable named dbg is called as usual.
Literals
| Gama | Means |
|---|---|
<1, 2, 3> | Vector3.new(1, 2, 3) |
<x, y> | Vector2.new(x, y) |
$ff8800, $f80 | Color.fromHex("#ff8800"). Three digits each stand for two, as in CSS |
$ff880080, $f808 | The string "#ff880080", since a Color has no alpha. UI colour properties such as Background take it |
asset "assets/Tree.gltf" | The string "assets/Tree.gltf". Gamma check and the language server warn when the file is not in the project |
Literals take fields, indexes and method calls like any value: <x, 0, z>.Unit, $000000:Lerp(color, 0.5). A vector literal can only start where an expression starts, so a < b still compares. Inside one, a comparison with > needs parentheses: <(a > b) and 1 or 0, 2, 3>.
Tools
| Command | Does |
|---|---|
Gamma check | Type checks .gma files against the engine's API. Use it in CI |
Gamma fmt | Re-indents .gma files |
Gamma transpile | Prints or writes the Luau a file becomes, with optional source maps |
Gamma port | Translates Luau, Roblox names included, to Gama |
Gamma lsp | The language server editors use |
None of these are in the web build.
What check reports. Gama errors, Luau type errors for .gma files and the .luau files they require, and Luau lints as warnings:
- unused variables, functions and parameters (prefix with
_to silence;selfis never reported) - unreachable code
- a
letthat shadows another in the same function (a nestedfnmay reuse an outer name) - duplicate table keys and conditions
- a
matchon anenumthat misses items - a tree key that its class does not have, or a value that does not fit it (these are errors, as they fail when the tree is built)
- wrong
string.formatarguments, and the other lints that catch mistakes
Lints about the Luau Gama generates are left out. Warnings don't fail check. It follows .luaurc aliases and languageMode, and --!strict at the top of a file; files outside a strict folder are checked non-strict. Write enum types as Enum.KeyCode.
Editors. The VS Code extension runs Gamma lsp and gives you errors as you type, completion (including paths in require and asset, a tree's properties and events, and the project's modules, which add their require at the top of the file when picked), hover, signature help, inferred type hints, go to definition, outline and workspace symbols, find references and rename (within a file), folding, formatting, semantic colouring, colour swatches on $ff8800, and quick fixes for Gama's own errors, unused names and mistyped tree keys and enum items. For Neovim, Helix and Zed, the tree-sitter grammar comes with highlight, scope and fold queries and the settings to start Gamma lsp.
Cheat sheet
Everything Gama adds to Luau, one line each.
| Gama | What it does |
|---|---|
let x = 1 | A variable |
const Max = 10 | A variable that cannot be assigned again |
fn add(a, b) return a + b end | A local function |
fn T.new() end, fn T:Get() end | A field or method of T |
fn(x) => x * 2 | A function of one expression |
fn f(n: number = 1) | A parameter with a default value |
let { x, y } = point, let [a, b] = list, for { x, y } in points do | Destructuring |
export let, export const, export fn, export enum, export class | What a module gives other files |
a != b | Not equal |
a ?? b, a ??= b | a, or b when a is nil; set a when it is nil |
a?.b, a?[k], a?:m() | Stop at nil |
x |> f(a) | f(x, a), for chains that read in order |
for i in 1..10 do, for i in 0..<n by 2 do | Count over a range |
match v when 1, 2 then ... else ... end | Compare one value with cases |
when 1..5, when { kind = "hit", damage }, when let n if n > 9 | Match a range, a table's shape, or anything, with a guard |
enum Mode { Fast, Slow } | Named strings and their type |
defer loading -= 1 | Run a statement when the fn ends, even by an error |
try ... catch err ... finally ... end | Catch an error, and clean up however the block ends |
class Counter ... end | Fields, methods and a constructor |
on signal(args) ... end, once signal do ... end | Connect to an event, every time or once |
on key Space, W do ... end, on keyup Escape do ... end | Run when a key is pressed or let go |
after 2 do ... end | Run once later |
every 1 do ... end, every 1 now do ... end | Run over and over |
spawn do ... end | Run now in a new thread |
wait 1, wait, wait until ready | Yield |
View { ... }, Part { ... }, Part "Floor" { ... } | Build a UI node or instance tree, optionally named |
dbg(x, y) | Print values with their source and line, and give them back |
<1, 2, 3>, <x, y> | Vector3, Vector2 |
$ff8800, $f80, $ff880080 | A Color, or a colour string with alpha |
asset "assets/Tree.gltf" | A path to a project file, checked by the tools |