Scripting
Lua API reference
Optional arguments are shown in [brackets]. Positions and directions are vec3 values; colours are
{r, g, b[, a]} tables. Functions marked (method) are called with a colon: e:destroy(). Properties
are read and written with a dot: e.position = vec3(0, 2, 0).
Script callbacks
| Function |
Called |
M:start() |
once, before the first update |
M:update(dt) |
every fixed step (60 per second); dt = step length in seconds |
M:on_collision(other, hit) |
touching another solid object; hit = {point, normal, speed} |
M:on_trigger_enter(other) / M:on_trigger_exit(other) |
something entered / left a trigger collider (this one, or one this object entered) |
M:on_animation_event(name) |
a keyframe clip reached an event key |
M:on_destroy() |
the object is about to be removed |
vec3
|
|
vec3(), vec3(v), vec3(x, y, z) |
make a vector (zero, all v, or x/y/z) |
.x .y .z |
components (read / write) |
a + b, a - b, -a, a * s, s * a, a * b, a / s, a == b |
arithmetic (a * b is per component) |
v:length(), v:normalized() |
length; unit vector (zero stays zero) |
a:dot(b), a:cross(b), v:copy() |
|
vec3.lerp(a, b, t), vec3.distance(a, b) |
|
Entity
Every object in the scene. self.entity is the script's own object.
|
|
e:valid() |
false once destroyed |
.id |
number, unique while the object exists |
.name |
read / write |
.position, .rotation, .scale |
vec3; rotation is Euler angles in degrees (pitch, yaw, roll) |
e:forward(), e:right(), e:up() |
unit vectors (forward is −Z) |
e:look_at(point) |
turn to face a point |
e:rotate_y(degrees) |
turn around the up axis |
e:teleport(pos) |
move instantly, physics body included |
e:destroy(), e:destroy_after(seconds) |
remove at the end of this step / after a delay; valid() turns false then |
e:clone() |
copy with the same model, collider, sound, light and script; returns the copy |
e:has(kind) |
"mesh", "body", "light", "camera", "script", "audio", "particles", "joint" |
.script |
the object's script table (nil without a script) |
Physics
|
|
e:velocity(), e:set_velocity(v) |
linear velocity (m/s) |
e:angular_velocity(), e:set_angular_velocity(v) |
radians/s |
e:add_impulse(v), e:add_force(v), e:add_torque(v) |
push it |
e:add_collider{type, shape, trigger, fit, mass, friction, bounciness, lock_rotation, center, half_extents, radius} |
give it a collider (replaces any existing one). Defaults: type = "static", shape = "mesh" for static and "hull" for dynamic, fit = true |
e:remove_collider() |
|
.motion, e:set_motion(kind) |
"static", "kinematic", "dynamic" (or "none" when there is no body) |
Shapes: "box", "sphere", "capsule", "hull" (convex hull), "mesh" (exact triangles; static and
kinematic only, dynamic falls back to hull).
Looks
|
|
.visible |
read / write |
e:set_tint(r, g, b[, a]) |
0..1 colour multiplier |
e:set_emissive(r, g, b) |
glow |
.texture, e:set_texture(path) |
base colour texture |
.mesh, e:set_mesh(path) |
the model ("builtin:cube", "models/…glb") |
e:set_material(name) |
a stock PBR set: brick, concrete, crate, dirt, grass, metal, planks, rock, sand, snow, tiles |
e:set_light(intensity[, r, g, b]), e:light_intensity() |
lights only |
.fov |
cameras only, degrees (5..150) |
Sound
|
|
e:play_sound(), e:stop_sound() |
the object's Audio Source |
.sound_playing |
read only |
.sound_volume, .sound_pitch |
read / write, live (engine revs, fades); volume 0..4, pitch 0.05..4 |
e:set_sound_volume(v), e:set_sound_pitch(p) |
the same as writing the properties |
e:set_sound(clip[, loop, spatial]) |
give it a sound and start it |
Animation and damage
|
|
e:play_animation(clip[, loop, speed]) |
a .anim keyframe clip, or the name of a clip inside a rigged model ("walk"; crossfaded). Negative speed plays backwards. |
e:stop_animation(), .animating |
keyframe clips |
e:animations() |
list of clip names in the rigged model |
.animation |
the skeletal clip playing now |
.damage |
0..1, with Crash Deformation |
e:dent(point, direction, speed) |
dent it by hand; returns the depth |
e:repair() |
restore the original shape |
Joints
|
|
e:add_joint{type, target, anchor, axis, min, max, motor_speed, motor_force, break_force, min_distance, max_distance, spring_frequency, spring_damping} |
connect it (types: "hinge", "ball", "slider", "spring", "distance", "fixed"); replaces any joint it had |
e:remove_joint() |
|
e:set_motor(speed) |
hinge: degrees/s, slider: m/s; 0 = off |
.joint_position |
hinge angle (degrees), slider offset (m), or distance (m) |
.joint_broken |
pulled apart by more than its break force |
Particle effects
|
|
e:emit([count]) |
release particles now (default: the burst size, or 20) |
.emitting |
read / write; turning it on restarts a one-shot effect |
e:set_particles(preset or {…}) |
add or replace the effect ("fire", {preset = "smoke", rate = 30}) |
e:remove_particles() |
|
.particles |
how many particles are alive |
Networking
|
|
e:is_mine(), e:has_authority() |
this peer owns / controls it |
e:net_id(), e:owner() |
network id; owning peer id |
e:set_var(name, value), e:var(name) |
synced variables |
scene
|
|
scene.find(name) |
first object with that name, or nil |
scene.entities([name]) |
list of every object (or every object with that name) |
scene.camera() |
the primary camera object |
scene.spawn{…} |
make an object; see below |
scene.spawn_prefab(path, position[, yaw]) |
place a copy of a .prefab; returns the list of new objects |
scene.destroy(e) |
|
scene.raycast(origin, dir, maxDist[, ignore]) |
nil or {entity, point, normal, distance} |
scene.screen_ray([x, y]) |
origin, direction through a screen point (default: the mouse) |
scene.world_to_screen(pos) |
x, y, visible |
scene.load(path), scene.reload() |
change level / restart after this step |
scene.time_scale([s]) |
slow motion (returns the current value) |
scene.gravity([v]) |
get / set gravity |
scene.spawn{
name = "Ball", mesh = "builtin:sphere", material = "metal", texture = nil, tint = {1, 1, 1, 1},
uv_scale = {1, 1}, roughness = 0.3, metallic = 1, emissive = {0, 0, 0},
position = vec3(0, 5, 0), rotation = vec3(0, 0, 0), scale = vec3(1, 1, 1),
body = { type = "dynamic", shape = "sphere", radius = 0.5, mass = 2, friction = 0.5, restitution = 0.3,
damping = 0.05, lock_rotation = false, trigger = false, fit = false, half_extents = vec3(0.5), center = vec3(0) },
sound = { clip = "sounds/hum.wav", volume = 1, pitch = 1, loop = true, play_on_start = true, spatial = true,
min_distance = 2, max_distance = 40 },
script = "scripts/ball.lua", fields = "speed = 3",
particles = "sparks", -- or { preset = "fire", rate = 60, ... } (see Particle effects)
lifetime = 5, -- remove it after 5 seconds
light = { type = "point", color = vec3(1, 0.8, 0.5), intensity = 20, range = 10 }, -- or "spot", "sun"
}
|
|
input.down(key), input.pressed(key), input.released(key) |
held / went down this step / went up |
input.mouse_down(b), input.mouse_pressed(b) |
0 left, 1 right, 2 middle |
input.mouse_delta(), input.mouse_position(), input.wheel() |
dx, dy; x, y; wheel steps |
input.move() |
x, y from WASD / arrows / left stick, length ≤ 1 (y = forward) |
input.action(name), input.action_pressed(name), input.action_released(name), input.axis(name) |
named actions from Project Settings > Input |
input.bind(action, {keys}[, {buttons}]) |
define an action from a script |
input.pad_connected([i]), input.pad_name([i]) |
gamepads |
input.pad_down(b[, i]), input.pad_pressed(b[, i]), input.pad_axis(a[, i]) |
buttons A B X Y LB RB LT RT START SELECT LSTICK RSTICK UP DOWN LEFT RIGHT (also CROSS CIRCLE SQUARE TRIANGLE); axes LX LY RX RY LT RT |
input.rumble(low, high, seconds[, i]) |
vibration |
Key names: A–Z, 0–9, F1–F12, SPACE, ENTER, ESCAPE, TAB, BACKSPACE, DELETE, UP,
DOWN, LEFT, RIGHT, LEFT_SHIFT (or SHIFT), RIGHT_SHIFT, LEFT_CONTROL (or CTRL),
RIGHT_CONTROL, LEFT_ALT, RIGHT_ALT. The first gamepad is also mapped onto keys and the mouse
automatically, so keyboard games work with a controller unchanged.
ui
Drawn for one frame; call them every update.
|
|
ui.text(str, x, y[, size, {r,g,b,a}, centered]) |
screen text; colours 0..255; negative x / y count from the right / bottom |
ui.rect(x, y, w, h[, {r,g,b,a}, centered]) |
a filled box; colours 0..1 or 0..255 |
ui.width(), ui.height() |
screen size in pixels |
ui.button(text, x, y, w, h[, {size, color, hover, text_color, center}]) |
a clickable button; returns clicked, hovered |
ui.image(path, x, y[, w, h, {r,g,b,a}, centered]) |
a picture from the project ("textures/logo.png"); 0 for its own size |
ui.measure(text[, size]) |
width of a text in pixels, for laying out |
audio
|
|
audio.play(clip[, pos, volume, pitch]) |
one-shot sound, 3D when pos is given |
audio.tone{wave, freq, to, time, attack, release, volume, vibrato, noise, pitch} |
a synthesised beep (wave: square, sine, triangle, saw, noise); returns its length |
audio.master([v]) |
master volume 0..1 |
audio.stop_all(), audio.voices() |
|
terrain
All take world X / Z. Edits during play in the editor are undone when you stop.
|
|
terrain.height(x, z) |
ground height, or nil off the terrain |
terrain.normal(x, z) |
vec3 or nil |
terrain.layer(x, z) |
index (1-based) and name of the paint layer there ("grass", "rock"…) |
terrain.raise(x, z, radius, metres) |
negative metres dig |
terrain.flatten(x, z, radius, y) |
level the ground to world height y |
terrain.smooth(x, z, radius[, strength]) |
|
terrain.paint(x, z, radius, layer[, strength]) |
|
terrain.add_tree(x, z[, type, scale]), terrain.remove_trees(x, z, radius) |
remove_trees returns how many it removed |
env
|
|
env.sky(path) |
skybox panorama ("" = procedural sky) |
env.sky_brightness(v), env.fog(density), env.exposure(v) |
|
env.tonemap(name) |
"aces", "agx", "neutral" |
env.sun(pitch[, yaw]), env.sun_brightness(v) |
the first directional light |
Saving, time and logging
|
|
storage.set(key, value), storage.get(key[, default]), storage.clear() |
save data that survives restarts (per game) |
time() |
seconds since play started |
log(...) / print(...) |
to the Console |
water_height(x, z) |
water surface height, or nil |
prefs (like PlayerPrefs)
Small settings and progress that survive restarts: volume, best score, unlocked levels. Saved to
saves/<bundle id>.prefs.json in the player's config folder (%APPDATA%\Ember on Windows,
~/.config/ember on Linux), at most once a second and when the game stops; prefs.save() writes at once.
|
|
prefs.set_int(key, n), prefs.get_int(key[, default]) |
whole numbers (get_* returns the default when the key is missing or holds another type) |
prefs.set_float, prefs.get_float |
numbers |
prefs.set_string, prefs.get_string |
text |
prefs.set_bool, prefs.get_bool |
true / false |
prefs.set(key, value), prefs.get(key[, default]) |
any value: tables, vec3 |
prefs.has_key(key), prefs.delete_key(key), prefs.delete_all(), prefs.keys(), prefs.save() |
|
storage.* (above) is the older, simpler version and keeps working.
http (web requests)
Requests run in the background; the function you pass is called on a later update with the response
res = {ok, status, body, headers, error} (res:json() decodes the body; header names are lower case).
http.get("https://api.example.com/scores?level=" .. http.encode(level), function(res)
if res.ok then
for _, s in ipairs(res:json()) do print(s.name, s.score) end
else
print("couldn't load scores:", res.status, res.error)
end
end)
http.post("https://api.example.com/scores", { name = "obi", score = 42 }, function(res) print(res.status) end,
{ Authorization = "Bearer " .. token })
|
|
http.get(url, fn[, headers]) |
|
http.post(url, body, fn[, headers]) |
a table body is sent as JSON, a string as is |
http.request{method, url, body, headers, timeout}, fn |
GET, POST, PUT, PATCH, DELETE, HEAD; timeout in seconds (30) |
http.encode(text) |
URL-encodes a value for a query string |
http.available(), http.backend(), http.pending() |
|
Only http:// and https:// URLs work, redirects are followed, responses are limited to 32 MB and 16
requests can run at once. Windows uses WinHTTP (built in); Linux and macOS use the system's libcurl; web
games use the browser's fetch, so the server has to allow your game's site (CORS). Android: not available
yet (http.available() is false and requests fail with a message). status is 0 when no response arrived
(offline, refused, timed out).
Anything a game sends can be read by its players, so never put a private API key in a script: talk to your
own server, which keeps the key.
json, timer, tween
|
|
json.encode(value[, pretty]), json.decode(text) |
tables, numbers, strings, booleans, vec3 |
timer.after(seconds, fn) |
calls fn once; returns an id |
timer.every(seconds, fn[, times]) |
repeats (times times, or until cancelled) |
timer.cancel(id), timer.cancel_all(), timer.count() |
|
tween.to(target, {field = value, ...}, seconds[, easing][, on_done]) |
animates numbers or vec3 on a table or an object: tween.to(self.entity, {position = vec3(0, 5, 0)}, 0.5, "out_back") |
tween.cancel(id), tween.running(id) |
|
Easings: linear, in_quad, out_quad, in_out_quad, in_cubic, out_cubic, in_out_cubic, in_sine,
out_sine, in_out_sine, in_back, out_back, out_elastic, out_bounce, in_bounce (also in, out,
in_out, smooth). math.ease(name, t) gives the curve itself.
file (the game's own folder)
Each game gets a private folder (saves/<bundle id>_files in the config folder) for bigger saves, level
editors, screenshots of data. Names may use folders ("levels/my level.json"); .., absolute paths and names
starting with a dot are refused. Files are limited to 64 MB.
|
|
file.write(name, text), file.append(name, text) |
write replaces the file in one step, so a crash never leaves half a save |
file.read(name) |
the contents, or nil |
file.exists(name), file.delete(name), file.list([folder]), file.folder() |
list marks folders with a trailing / |
system, clipboard, math
|
|
system.platform() |
"windows", "linux", "macos", "web" or "android" |
system.language() |
two letters from the OS settings, e.g. "en", "fr" |
system.cpu_count(), system.fps(), system.screen() |
|
system.time(), system.date([format]) |
seconds since 1970; local date (strftime format, default %Y-%m-%d %H:%M:%S) |
system.open_url(url) |
opens a web page in the player's browser |
system.fullscreen([on]) |
switch / read full screen |
system.quit() |
quits the game (in the editor: stops play) |
clipboard.get(), clipboard.set(text) |
|
math.lerp(a, b, t), math.inverse_lerp(a, b, v), math.clamp(v, lo, hi), math.remap(v, a, b, c, d) |
lerp also works on vec3 |
math.smoothstep(a, b, v), math.round(v[, decimals]), math.sign(v), math.approach(cur, target, step), math.ease(name, t) |
|
Sandbox
Scripts can't run programs or reach files outside the game: io, os.execute, os.remove, os.rename,
os.exit, dofile and loadfile are removed, and load only accepts source text (crafted
bytecode can crash Lua). os.time, os.clock and os.date still work; os.getenv only reads variables named EMBER_* or GAME_*.
net (multiplayer)
|
|
net.host([port, max_players, transport]), net.join([address, port, transport]), net.leave() |
transport: "enet" (default), "photon", "eos" |
net.is_server(), net.is_client(), net.online(), net.connected(), net.error() |
|
net.id(), net.ping(), net.players(), net.player_name(id), net.set_name(name) |
|
net.on(event, fn) |
"player_joined", "player_left", "kicked", "cheat", or an RPC / command / message name |
net.spawn(desc[, owner]), net.destroy(e) |
networked objects (desc as in scene.spawn) |
net.rpc(name, data) |
server → everyone |
net.command(name, data) |
client → server |
net.send_to(peer, name, data) |
one player |
net.set(name, value), net.get(name) |
shared game state |
net.voice(on[, push_to_talk_key]), net.voice_proximity(metres), net.talking([peer]) |
voice chat |
net.kick(peer[, reason]), net.allow_teleport(e), net.kick_reason(), net.stats(), net.guard_stats() |
|
anticheat
|
|
anticheat.active() |
the checks are running |
anticheat.on_violation(fn) |
fn(kind, detail) |
anticheat.secure(name, value), anticheat.get(name[, default]), anticheat.add(name, delta) |
tamper-resistant numbers (score, money) |
anticheat.report(kind[, detail]), anticheat.violations() |
|
|
|
vr.active(), vr.head_position(), vr.head_forward() |
|
vr.hand_position(h), vr.hand_forward(h), vr.hand_tracked(h) |
h = "left" or "right" |
vr.trigger(h), vr.grip(h), vr.thumbstick(h), vr.button(h, "primary" / "secondary") |
|
platform.steam(), platform.unlock_achievement(id) |
no-ops unless Steam is switched on |