MotaEngine

Lua Scripting API

MotaEngine can run gameplay scripts written in Lua. This page is the complete reference for what a script can call: the global mota table, the lifecycle callbacks the engine invokes on a script, and the rules scripts run under.

Lua scripting is a gameplay layer on top of a C++ game. The engine hosts the Lua runtime: any entity with a ScriptComponent runs its script, in windowed games, headless runs and dedicated servers alike. Your C++ game module decides which entities get which scripts; scripts then drive behaviour through the mota functions listed here. For the C++ side, see sdk-reference.md.

Contents

Overview

Runtime. On Windows, Linux and macOS scripts run on LuaJIT (Lua 5.1 compatible). On Android and iOS they run on Lua 5.4, because LuaJIT cannot be built for those platforms. If your game ships on mobile, write scripts in the subset both versions share: avoid LuaJIT-only libraries (bit, jit, ffi), Lua 5.4-only syntax (integer division //, bitwise operators, <const>), and use table.unpack or unpack where you need unpack.

One Lua state. Every script in a ScriptEngine shares a single Lua state. Global variables are therefore visible to (and can be overwritten by) every other script. Keep per-entity state in local variables, as described in Writing a script.

Sandbox. The standard libraries are opened, then os, io, loadfile, dofile, require, package and debug are removed (set to nil). Scripts cannot touch the file system, run system commands, load native modules or reach LuaJIT's ffi. string, table, math, coroutine and the rest of the base library remain available. Even so, treat the sandbox as a guard against accidents rather than a hardened security boundary: run scripts you ship yourself, not scripts downloaded from players.

The mota table. All engine functions live on the global table mota (for example mota.log, mota.getPosition). There are no other engine globals and no sub-tables.

Entity handles are numbers. An entity is passed to and returned from scripts as a single number that encodes both the entity's slot and its generation. Treat it as opaque: compare it, store it, pass it back to mota functions. A handle to a destroyed entity stays dead even after the engine reuses its slot for a new entity, so a stale handle can never move or destroy the wrong entity (mota.isAlive tells you whether it still exists). From C++, ScriptEngine::EntityToScript and ScriptEngine::EntityFromScript convert between an EntityID and the number a script sees.

Vectors are separate numbers. Positions, directions, velocities and scales are passed as three numbers x, y, z, and returned as three return values. Rotations are quaternions passed as four numbers x, y, z, w. The world is Y-up (gravity points along negative Y).

local x, y, z = mota.getPosition(entity)
mota.setPosition(entity, x, y + 1.0, z)

Missing arguments. Required arguments are checked: passing a non-number where a number is expected, or omitting a required argument, raises a Lua error ("bad argument #2 to ..."). Optional arguments are marked [name=default] in the signatures below.

Setting up scripting in your game

Without C++ (script-only games). A project whose .motaproj has an empty gameModule is a complete game made of editor scenes plus Lua: the engine loads the project's startupScene, builds the input context from its inputBindings, and runs its startupCommands (console commands and CVars, such as r.ground.plane 0). In the editor, attach a script with Add Component > Lua Script. You can also drop a .lua file from the Content Browser onto the viewport or onto the Script field. The Parameters field holds per-entity settings that scripts read with mota.getParam. Set the startup scene, bindings and startup commands under Project Settings > Maps & Modes / Input. projects/EmberRun is a complete example:

MotaEngine.exe --game --project=projects/EmberRun/EmberRun.motaproj

From C++. The engine creates the Lua runtime at startup, connects it to the world, physics, input and audio, and registers the scripting systems. Your game only attaches scripts to entities. To run a script on an entity, add a ScriptComponent with the script's path:

#include <motaware/scripting/script_component.h>

mota::scripting::ScriptComponent sc;
std::strncpy(sc.scriptPath, "projects/MyGame/Scripts/spinner.lua", sizeof(sc.scriptPath) - 1);
world.AddComponent<mota::scripting::ScriptComponent>(entity, sc);

ScriptComponent fields:

FieldMeaning
scriptPathPath to the .lua file (up to 255 characters).
enabledtrue by default. While false, the script is neither started nor updated.
handle, initializedManaged by the engine. Leave at their defaults.

Scripts are read through the engine's virtual file system: a mounted pak (for example the one --package produces) is searched first, then loose files on disk. Loose paths are relative to the process working directory, the same convention as other project assets.

The runtime is available to your game module as ctx.scriptEngine (mota::scripting::ScriptEngine*). Use it to run a chunk directly (LoadScriptFromString), read globals (GetGlobalNumber), or register your own functions: GetLuaState() returns the underlying lua_State* (as void*) for the standard Lua C API. Do not close that state.

Writing a script

A script file is a Lua chunk that returns a table. The engine looks up the callback functions on that table by name:

-- Scripts/spinner.lua
local angle = 0.0          -- per-entity state (see below)

return {
    OnCreate = function(entity)
        mota.log("spinner attached to entity " .. entity)
    end,

    OnUpdate = function(entity, dt)
        angle = angle + dt
        local half = angle * 0.5
        -- rotate around the Y axis
        mota.setRotation(entity, 0.0, math.sin(half), 0.0, math.cos(half))
    end,
}

All callbacks are optional. A script that returns something other than a table still loads (its top-level code runs once) but receives no callbacks.

Per-entity state. The script file is loaded and executed separately for each entity that uses it, so every entity gets its own copy of the chunk's local variables (like angle above). Globals, in contrast, are shared by every script and every entity, so avoid them for per-entity data.

Lifecycle callbacks

CallbackCalled withWhen
OnCreate(entity)the entity handleOnce, right after the script is loaded for that entity, and again after a hot reload.
OnUpdate(entity, dt)the entity handle and the step length in secondsEvery simulation step while the component is enabled.
OnDestroy(entity)the entity handleOnce, when the entity is destroyed, its ScriptComponent is removed, or the engine shuts down.

Timing details:

  • Scripts are loaded and OnCreate runs during the simulation step after the ScriptComponent is added (before the step's regular update work).
  • OnUpdate runs inside the fixed-timestep simulation, so dt is the simulation step (1/60 s by default; servers can change it with --tickrate). When a frame needs several simulation steps, OnUpdate runs once per step.
  • Setting enabled = false on the component pauses OnUpdate; setting it back to true resumes it. OnCreate is not called again.
  • When an entity is destroyed or loses its ScriptComponent, OnDestroy runs during the next simulation step. By then the entity is already gone, so use OnDestroy to clean up script-side state (tables, counters, spawned entities you track); mota.getPosition and similar functions return identity values for it.
  • At engine shutdown every running script receives OnDestroy while the world, physics and audio are still alive.

Errors

  • Load errors (syntax errors, or a runtime error in the chunk's top-level code) are written to the engine log as Script error in '<path>': <message>. A missing file is logged as Failed to read script: <path>. The entity's script stays unstarted and is not retried every step: the engine tries again once the file changes on disk (or the component's path changes), so fixing the file while the game runs starts the script.
  • Errors inside OnCreate, OnUpdate or OnDestroy stop that one call and are logged as OnUpdate error in '<path>': <message> (and likewise for the other callbacks). An error that repeats every step is logged once, and again only when the message changes. The script keeps running; the next step calls it again. The C++ side can read the most recent error with ScriptEngine::GetLastError().

Error messages name the script by its path and line number.

Reloading scripts

Outside Shipping builds (Debug and Development), the engine checks loose script files for changes every half second of simulation time. When a file changes, it is re-read and re-run, its new callback table replaces the old one, and OnCreate is called again for that entity. The chunk's local state starts fresh, so OnCreate is the place to rebuild it. If the new version fails to load, the error is logged and the previous version keeps running.

Shipping builds do not watch files. Scripts read from a pak never reload. From C++, ScriptEngine::ReloadScript(handle) reloads one script on demand (the handle is in the entity's ScriptComponent::handle).

Logging

mota.log

mota.log(message)
ParameterTypeDescription
messagestringText to write. Numbers are accepted and converted.

Returns nothing. Writes [Lua] <message> to the engine log at Info level in the Scripting category. Use tostring for other values (booleans, nil, tables).

mota.log("health = " .. health)
mota.log("grounded: " .. tostring(isGrounded))

Entities

mota.createEntity

local entity = mota.createEntity()

Creates a new entity with a default Transform (origin, no rotation, scale 1) and returns its handle, so the transform functions work on it straight away. Returns nil if no world is connected. Other components (meshes, bodies, scripts) are added from C++.

mota.isAlive

local alive = mota.isAlive(entity)

Returns true while the entity exists, false once it has been destroyed (even if its slot now belongs to a newer entity).

mota.destroyEntity

mota.destroyEntity(entity)
ParameterTypeDescription
entitynumberHandle of the entity to destroy.

Returns nothing. Destroys the entity if it is alive; does nothing otherwise. It is safe to call from any callback, including on the entity whose OnUpdate is running: that entity receives OnDestroy on the next step.

Transforms

These functions read and write the entity's Transform component. If no world is connected, or the entity is not alive or has no Transform, the getters return the identity values shown below and the setters do nothing.

FunctionReturnsDescription
mota.getPosition(entity)x, y, zWorld position. Identity value: 0, 0, 0.
mota.setPosition(entity, x, y, z)nothingSets the position.
mota.getRotation(entity)x, y, z, wRotation as a quaternion. Identity value: 0, 0, 0, 1.
mota.setRotation(entity, x, y, z, w)nothingSets the rotation. Pass a unit quaternion.
mota.getScale(entity)x, y, zScale. Identity value: 1, 1, 1.
mota.setScale(entity, x, y, z)nothingSets the scale.

All parameters after entity are numbers. The quaternion component order is x, y, z, w for both the getter and the setter.

On an entity with a dynamic or static physics body, mota.setPosition and mota.setRotation also teleport the body. setPosition clears a dynamic body's velocity, which makes it the call to use for respawns. Kinematic bodies follow their Transform anyway. To move a dynamic body continuously, use the physics functions instead.

-- Bob up and down around the starting height.
local baseY
local t = 0.0

return {
    OnCreate = function(entity)
        local _, y, _ = mota.getPosition(entity)
        baseY = y
    end,
    OnUpdate = function(entity, dt)
        t = t + dt
        local x, _, z = mota.getPosition(entity)
        mota.setPosition(entity, x, baseY + math.sin(t * 2.0) * 0.25, z)
    end,
}

Physics

mota.raycast uses world coordinates. The body functions take a physics body ID, which is not the same as an entity handle; get it with mota.getBody(entity).

mota.getBody

local body = mota.getBody(entity)

Returns the physics body ID of the entity's RigidBody, or nil when the entity has no RigidBody or its body has not been added to the physics world yet (that happens during the first physics step after the component is added, so call getBody from OnUpdate, or retry, rather than relying on it in OnCreate).

mota.raycast

local hit, x, y, z, distance = mota.raycast(ox, oy, oz, dx, dy, dz [, maxDistance=100])
ParameterTypeDescription
ox, oy, oznumbersRay origin.
dx, dy, dznumbersRay direction. It is normalized for you. A zero vector returns no hit.
maxDistancenumber, optionalMaximum ray length. Default 100.
ReturnTypeDescription
hitbooleantrue if the ray hit a body.
x, y, znumbersHit point (0, 0, 0 when nothing was hit).
distancenumberDistance from the origin to the hit point (0 when nothing was hit).

Without a physics world it returns false, 0, 0, 0, 0.

mota.addForce

mota.addForce(bodyID, fx, fy, fz)

Applies a force (newtons) to the body's center of mass for the next physics step. Call it every step for a continuous push. Returns nothing.

mota.addImpulse

mota.addImpulse(bodyID, ix, iy, iz)

Applies an instantaneous impulse (an immediate change in momentum, suited to jumps, hits and explosions). Returns nothing.

mota.getVelocity

local vx, vy, vz = mota.getVelocity(bodyID)

Returns the body's linear velocity in units per second. Without a physics world it returns 0, 0, 0.

mota.setVelocity

mota.setVelocity(bodyID, vx, vy, vz)

Overwrites the body's linear velocity. Returns nothing.

The ray reports the first body it meets, including the body of the entity doing the cast, so start rays outside your own collider.

-- Jump when grounded. The character's collider extends 1.0 below its position.
OnUpdate = function(entity, dt)
    local body = mota.getBody(entity)
    if not body then return end
    local x, y, z = mota.getPosition(entity)
    local grounded = mota.raycast(x, y - 1.05, z, 0, -1, 0, 0.1)
    if grounded and mota.isActionPressed("Jump") then
        local vx, _, vz = mota.getVelocity(body)
        mota.setVelocity(body, vx, 0, vz)
        mota.addImpulse(body, 0, 400, 0)
    end
end,

Triggers

A script on an entity whose RigidBody has Is Trigger set receives two more callbacks:

CallbackCalled withWhen
OnTriggerEnter(self, other)the trigger and the entering entityA non-trigger RigidBody starts overlapping the trigger.
OnTriggerExit(self, other)the trigger and the leaving entityIt stops overlapping. Not called when other was destroyed.

The overlap test uses each collider's axis-aligned bounds around its Transform position (rotation is ignored). It runs every simulation step after OnUpdate, so it sees static, kinematic and dynamic bodies alike.

-- Scripts/coin.lua on a trigger sphere
return {
    OnTriggerEnter = function(self, other)
        if mota.getName(other) == "Player" then
            score = (score or 0) + 1
            mota.destroyEntity(self)
        end
    end,
}

Finding entities and script parameters

FunctionReturnsDescription
mota.findEntity(name)entity or nilThe first entity whose name (editor outliner / NameComponent) equals name.
mota.findEntities(prefix)tableEvery entity whose name starts with prefix, as an array.
mota.getName(entity)string or nilThe entity's name.
mota.getParam(entity, key [, default])number, boolean, string or defaultA value from the entity's ScriptComponent Parameters ("speed=2; axis=x; loop=true"). Numbers and true/false are converted; a missing key returns default (nil if omitted).

Parameters let one script serve many entities: a patrol script reads its own range and speed instead of hard-coding them.

Camera, HUD and appearance

These go through the host application. In headless runs they do nothing, and mota.hudShow accepts any known element name.

FunctionDescription
mota.setCamera(ex, ey, ez, tx, ty, tz [, fov=60])View from the eye point toward the target point. Call it every update for a follow camera. Overrides the editor camera during play.
mota.releaseCamera()Hand the view back.
mota.hudText(text)The objective line at the top centre.
mota.hudStatus(text)The status line under the bars.
mota.hudHealth(fraction)The health bar, 0 to 1.
mota.hudScore(n) / mota.hudScoreLabel(label)The counter under the bars and its label (default Gold).
mota.hudShow(element, visible)Show or hide a stock HUD element: health, mana, score, ammo, minimap, compass, crosshair. Raises an error for other names.
mota.hudBanner(text [, seconds=2])Big centred text (titles, "WAVE 3", "GAME OVER"). seconds <= 0 keeps it until replaced; "" hides it.
mota.setColor(entity, r, g, b [, a=1])Material base colour (adds a material if the entity has none).
mota.setEmissive(entity, r, g, b)Material emissive colour; values above 1 glow.
mota.setVisible(entity, visible)Show or hide the entity's mesh.

Scenes and game flow

FunctionReturnsDescription
mota.spawn(prefab, x, y, z [, yaw=0])entity or nilInstantiate a .prefab file (with its children and scripts) at a position, rotated yaw radians about +Y. Scripts on it start next step. Use it for bullets, enemies, pickups and effects.
mota.loadScene(path)booleanReplace the running scene with path after the current step. Returns false if the file does not exist. Globals survive the switch, so a global table can carry lives or a score from level to level.
mota.quit()nothingEnd the game (on Android the app closes). Does nothing on iOS, where apps must not quit themselves.
mota.canQuit()booleanfalse on iOS: hide a Quit menu entry there (the player leaves with the home gesture).
mota.getSocket(entity, name)x, y, z or nilWorld position of a socket on the entity's model: a model socket (Static Mesh Editor, <model>.meshsettings) or a bone socket (Skeleton Editor, <model>.motaskel; it follows the animated pose when the entity has an Anim Blueprint).
mota.showWidget(path) / mota.hideWidget(path)boolean / nothingShow a UI Widget asset (.motawidget, made in the Widget Designer) over the game, in the 1920 x 1080 UI space; showing it again keeps the one up. false if the file does not load.
mota.setWidgetValue(name, value)nothingWhat every {{name}} binding in shown widgets displays (numbers and booleans become text), e.g. mota.setWidgetValue("score", score).
mota.widgetClicked(buttonName)booleantrue once per click on a button whose widget name is buttonName (poll it in OnUpdate).
mota.dataTable(path)table or nilA data table (.motatable, made in the Data Table editor) as rows[rowName][columnName] with numbers, strings and booleans by column type, e.g. local loot = mota.dataTable("projects/MyGame/Data/loot.motatable"); print(loot.Sword.Damage). Cached; nil if the file does not load.
mota.evalCurve(path, time [, curve])numberThe value of a curve (.motacurve, made in the Curve editor) at time: the named curve, or the first. Clamped outside its keys; 0 if the file does not load.
mota.setAnimFloat(e, name, value) / mota.setAnimBool(e, name, b) / mota.setAnimInt(e, name, n)booleanSet a parameter of the entity's Anim Blueprint (its state machine's transition rules and blend trees read them). false when the entity has no running anim blueprint. A float param named Speed is filled automatically from how fast the entity moves on the ground.
mota.getAnimState(e)stringThe anim blueprint's current state ("" when not animated).
mota.playSequence(path [, loop=false])booleanPlay a level sequence (.motaseq, made in the Sequencer): its transform / property tracks move named entities, audio sections play, camera cuts switch the view to the named camera entity until it ends, event keys appear in the log. Asking again restarts it. false if the file does not load.
mota.stopSequence(path)nothingStop a sequence started with mota.playSequence. To play one when the level starts, add a Sequence Actor component to any entity instead.
mota.saveNumber(key, value)nothingStore a number that persists between runs (high scores, settings): Saved/<Project>/script_values.json.
mota.loadNumber(key [, default])numberRead it back; default (or nil) when never saved.

In development builds the dev console (`) has a lua <code> command that runs a chunk in the same Lua state. --exec="lua ..." does the same from the command line, for example to set test globals.

FunctionReturnsDescription
mota.exec(command)stringRun a console command (the same ones the dev console takes, such as r.shadow.cascades 2) and return its output. Use it for graphics settings.

A script-only game builds its whole front end (title screen, level select, settings, pause, game over) from engine menus. A menu is a centred list of items drawn over the running scene. Players drive it with the mouse, the keyboard (Up/Down select, Left/Right adjust, Enter activates, Esc goes back) or a gamepad (D-pad or left stick, A activates, B or Start goes back).

mota.defineMenu

mota.defineMenu(name, {
    title    = "EMBER RUN",
    backdrop = 0.6,                       -- 0 = scene fully visible, 1 = opaque
    status   = function() return "Best: 41.2 s" end,   -- line under the title (string or function)
    info     = { "Line of text", "..." }, -- paragraphs above the items (How to Play, Credits)
    back     = function() mota.popMenu() end,         -- Esc / B / Start
    sounds   = { move = "Audio/ui_move.wav", select = "Audio/ui_select.wav", volume = 0.5 },
    items    = {
        { "Play", function() startGame() end },
        { "Music Volume", value = function() return "80%" end,
                          adjust = function(delta) changeMusic(delta) end },
    },
})

Each item is { label, fn }; an item with value (a string or a function that returns one) shows that value on the right, and adjust(delta) is called with -1 / +1 for Left/Right, and with +1 when the row is clicked or activated (a value row ignores fn). Calling mota.defineMenu again with the same name rebuilds that menu in place, so a level-select list can be regenerated each time it opens. Value and status functions run every frame the menu is visible.

FunctionReturnsDescription
mota.showMenu(name)nothingShow the menu in place of every other screen (title, game over).
mota.pushMenu(name)nothingOpen the menu over the current screen (pause, settings opened from pause).
mota.popMenu()nothingClose the top menu, returning to whatever was under it. Never removes the HUD.
mota.hideMenus()nothingClose every menu and return to the HUD.
mota.setPaused(paused) / mota.isPaused()nothing / booleanStop or resume the simulation step: physics and script OnUpdate stop while paused, menus keep working.
mota.setFullscreen(on) / mota.isFullscreen()nothing / booleanBorderless fullscreen or windowed.

showMenu and pushMenu raise an error for a name that was never defined. In --headless processes there are no screens: menu functions do nothing, so the same scripts run under the autopilot or on a server.

A typical pause flow:

mota.defineMenu("pause", {
    title = "PAUSED", backdrop = 0.55,
    back  = function() mota.popMenu(); mota.setPaused(false) end,
    items = {
        { "Resume",  function() mota.popMenu(); mota.setPaused(false) end },
        { "Quit to Title", function() mota.setPaused(false); mota.loadScene("projects/MyGame/Scenes/title.json") end },
    },
})

-- in a GameManager's OnUpdate, on the press edge of a "Pause" action:
if pausePressed and not mota.isPaused() then
    mota.setPaused(true)
    mota.pushMenu("pause")
end

projects/EmberRun/Scripts/game.lua is a complete example: title, level select, settings (saved with mota.saveNumber), how to play, credits, pause, level complete, game over and victory menus.

Mouse

FunctionReturnsDescription
mota.mousePosition()x, yCursor position in pixels inside the game view (the editor viewport in play mode).
mota.mouseToWorld([planeY=0])hit, x, y, zThe point under the cursor on the horizontal plane y = planeY, through the current camera. Use it to aim in top-down games. hit is false headless or when the ray misses the plane.

Input

Input functions query the engine's input mappings by name: the action and axis names your game defines in its input bindings. A script-only project defines them in its .motaproj (inputBindings, editable under Project Settings > Input). Without any, it gets MoveForward/MoveRight (WASD, arrows, left stick), LookX/LookY, Jump, Fire, Interact, Sprint and Pause. They work once the input system is connected; otherwise they return false / 0. Unknown names also return false / 0.

FunctionReturnsDescription
mota.isActionPressed(action)booleantrue while the mapped action is triggered or held.
mota.isKeyDown(action)booleanSame as isActionPressed. Despite its name it takes an action name, not a key name or key code.
mota.getAxis(axis)numberCurrent value of the mapped axis, normally in the range -1 to 1.
OnUpdate = function(entity, dt)
    local speed = 5.0
    local x, y, z = mota.getPosition(entity)
    x = x + mota.getAxis("MoveRight") * speed * dt
    z = z + mota.getAxis("MoveForward") * speed * dt
    mota.setPosition(entity, x, y, z)
end,

Audio

Sounds are referenced by file path (WAV, MP3, FLAC and the other formats the audio engine decodes). A clip is loaded the first time it is played and kept for reuse. Both functions return true if the sound started, and false when the file cannot be loaded (a warning is logged once per path) or when the process has no audio engine, such as a dedicated server.

mota.playSound

local started = mota.playSound(path [, volume=1.0])
ParameterTypeDescription
pathstringSound file path.
volumenumber, optionalVolume multiplier. Default 1.0.

Plays the sound once, non-positional, on the SFX bus.

mota.playSound3D

local started = mota.playSound3D(path, x, y, z [, volume=1.0])
ParameterTypeDescription
pathstringSound file path.
x, y, znumbersWorld position of the sound.
volumenumber, optionalVolume multiplier. Default 1.0.

Plays the sound once at a world position, attenuated by distance from the listener, on the SFX bus.

Music and volume

FunctionReturnsDescription
mota.playMusic(path [, volume=1.0])booleanPlay one looping track on the Music bus. It keeps playing across mota.loadScene; asking for the track that is already playing does nothing, so every level can call it safely. A different path replaces the current track.
mota.stopMusic()nothingStop the music track.
mota.setVolume(bus, volume)nothingSet a bus volume, 0 to 1. bus is "master", "music", "sfx" or "dialogue". Not saved: store settings with mota.saveNumber and re-apply them at startup.
mota.getVolume(bus)numberCurrent bus volume (1 without an audio engine).

Settings menu

FunctionReturnsDescription
mota.settingsMenu()booleanOpen the engine's Settings menu: master, music and effects volume, display, look sensitivity, invert look, and Voice Chat when the game uses voice. Saved with the player's settings. mota.pushMenu("settings") opens it too unless you define a menu called "settings".
mota.settingsRows{items = {...}, sounds = {...}}nothingYour game's own rows in that menu (above Back), in the same item format as mota.defineMenu: { "Shadows", value = fn, adjust = fn } or { "Reset", fn }. Call it once (e.g. where you define your menus); mota.settingsMenu() then shows them. On an engine without it (mota.settingsRows == nil) keep a menu of your own.
mota.isHeadless()booleanTrue with no window or player (--headless, dedicated servers, automated runs): skip player-only work such as moving saved settings.
mota.lookSensitivity()numberThe player's look speed multiplier (1 = your game's own speed, 0.25 - 3). Multiply your camera's turn speed by it.
mota.invertLook()booleanWhether the player wants up to look down.

Voice chat

Players in an online game can talk to each other. The game opts in with "voice": {"enabled": true} in its project settings (see the SDK reference); each player then turns voice on in the Voice menu (off by default). Voice goes through the game's server, never straight between players, and is never recorded.

FunctionReturnsDescription
mota.voiceMenu()booleanOpen the engine's Voice menu (on/off, push-to-talk or open mic, the push-to-talk key, microphone, sensitivity, volumes, Test microphone, and a mute row for every player heard). Same as mota.pushMenu("voice"); put it in your Settings menu.
mota.voiceEnable(on)nothingTurn the player's voice chat on or off (saved with their settings).
mota.voiceEnabled()booleanWhether the player has voice on.
mota.voiceMode(mode)nothing"ptt" (push-to-talk, the default) or "open" (open mic).
mota.voiceTalk(held)nothingHold push-to-talk from a script (a touch button, a radio item).
mota.voiceChannels(channels)nothingWhat the player transmits on: "team", "proximity", "all", or combined, e.g. "team+proximity".
mota.voiceMute(id [, muted=true])nothingStop hearing a player (the server stops sending their voice).
mota.voiceMuted(id)booleanWhether you muted that player.
mota.voiceTalking([id])table or booleanThe ids of the players talking now, or whether player id is.
mota.voiceTransmitting()booleanWhether this player is being heard right now.
mota.voiceName(id, name)nothingThe name shown for a player on the HUD (Talking: Ana) and in the Voice menu.
mota.voicePlayer(connection, id, team)booleanServer: who a connection is (the id others know them by) and their team. False on a client.
mota.voicePosition(connection, x, y, z)booleanServer: where a player is, for proximity voice. False on a client.

The HUD's "voice" element (bottom left) shows who is talking; hide it with mota.hudShow("voice", false).

Math

Helpers for working with x, y, z triples. These need no engine subsystem and always work. The standard math library is available as well.

FunctionReturnsDescription
mota.distance(x1, y1, z1, x2, y2, z2)numberDistance between two points.
mota.normalize(x, y, z)x, y, zThe vector scaled to length 1. A vector shorter than 0.0001 is returned unchanged.
mota.lerp(a, b, t)numbera + (b - a) * t. t is not clamped.
mota.randomRange(min, max)numberA random number between min and max (inclusive).
-- Move toward a target point at a fixed speed.
local function moveToward(entity, tx, ty, tz, speed, dt)
    local x, y, z = mota.getPosition(entity)
    local dist = mota.distance(x, y, z, tx, ty, tz)
    if dist < 0.01 then return true end
    local nx, ny, nz = mota.normalize(tx - x, ty - y, tz - z)
    local step = math.min(speed * dt, dist)
    mota.setPosition(entity, x + nx * step, y + ny * step, z + nz * step)
    return false
end

mota.randomRange uses the C runtime's random generator, which the engine does not seed; use math.random (after math.randomseed) if you need control over the sequence.

Time

mota.getTime

local seconds = mota.getTime()

Returns the simulation time in seconds since the script system started: the sum of every step's dt. It advances once per simulation step, before that step's OnUpdate calls, so all scripts see the same value within a step.

Data tables

Data tables let designers tune gameplay values in CSV files without touching code or scripts. At startup the engine loads every *.csv file in the Data/Tables folder next to the executable; each file becomes a table named after the file (without .csv). The engine also provides a built-in weapons table if the game does not supply one.

CSV format: the first line holds column names, and the first column of each row is the row key. Values are split on commas (quoted fields are not supported). Each cell gets a type from its text:

Cell textStored asRead with
true or falsebooleandataTableGetBool
contains a . (for example 15.0)number (float)dataTableGetFloat
a whole number (for example 15)integerdataTableGetInt (or dataTableGetFloat)
anything elsestringdataTableGetString

Each getter returns values of its own type, with one convenience: dataTableGetFloat also reads whole-number cells, so 15 and 15.0 both read as 15 through it.

FunctionReturnsDescription
mota.dataTableHas(table)booleantrue if a table with this name is loaded. Takes only the table name.
mota.dataTableGetFloat(table, row, column [, default=0])numberFloat value of the cell.
mota.dataTableGetInt(table, row, column [, default=0])integerInteger value of the cell.
mota.dataTableGetBool(table, row, column [, default=false])booleanBoolean value of the cell.
mota.dataTableGetString(table, row, column [, default=""])stringString value of the cell.

table, row and column are strings. Every getter returns default when the table, row or column does not exist, or when the cell holds a different type.

Given Data/Tables/weapons.csv:

key,damage,range,automatic,name
pistol,15.0,25.0,false,Pistol
rifle,28.0,80.0,true,Rifle
if mota.dataTableHas("weapons") then
    local dmg  = mota.dataTableGetFloat("weapons", "rifle", "damage")        -- 28.0
    local auto = mota.dataTableGetBool("weapons", "rifle", "automatic")      -- true
    local name = mota.dataTableGetString("weapons", "pistol", "name")        -- "Pistol"
    local none = mota.dataTableGetFloat("weapons", "missing", "damage", -1)  -- -1
end

Experiments

Experiments (A/B tests and feature flags) assign each player a stable variant of a named experiment. Your game registers its experiments in C++ at startup; scripts read the local player's variant.

mota.experimentVariant

local variant = mota.experimentVariant(name [, default=""])
ParameterTypeDescription
namestringExperiment name.
defaultstring, optionalReturned when the experiment does not exist or has no variant for this player. Default "".

Returns the variant name (string) assigned to the local player. The assignment is deterministic for a given player and experiment, so it stays the same across sessions. The engine registers one sample experiment, ui.menu_layout, with the variants classic and compact.

if mota.experimentVariant("ui.menu_layout", "classic") == "compact" then
    -- use the compact layout
end

Headless and dedicated servers

Lua scripts run the same way in windowed, --headless and --server processes. Things to keep in mind on a server:

  • There is no local player input, so input functions return false / 0.
  • There is no audio engine, so mota.playSound, mota.playSound3D and mota.playMusic return false without playing anything.
  • There are no screens, so the menu functions do nothing.
  • Entity, transform, physics, math, time, data table and experiment functions work normally.

Known limitations

  • One shared Lua state. Globals are visible to every script; keep per-entity data in local variables.
  • OnDestroy runs after the fact. It is called on the step after the entity is destroyed, when the entity can no longer be read.
  • Handles are exact up to about two million reuses of one entity slot. Beyond that, a stale handle may stop resolving rather than resolving to the wrong entity.
  • mota.isKeyDown takes an action name, like mota.isActionPressed; there is no raw key query.
  • Scripts cannot add or remove components other than through mota.createEntity (which adds a Transform) and mota.destroyEntity; mota.setColor/setEmissive add a material when the entity has none. Place entities in the editor (or a prefab) and register your own functions from C++ for anything more.
  • Trigger overlap is axis-aligned: a rotated box trigger is tested as if it were not rotated.

Complete example

A pickup that spins, bobs, plays a sound and removes itself when the player comes close. The game sets the global playerEntity from C++ (for example with ctx.scriptEngine->LoadScriptFromString("playerEntity = " + std::to_string( mota::scripting::ScriptEngine::EntityToScript(player)))).

-- Scripts/pickup.lua
-- Per-entity state: this chunk runs once for each entity that uses the script.
local t = 0.0
local baseY = 0.0
local spinSpeed = 2.0
local pickupRadius = 1.5

pickupsCollected = pickupsCollected or 0   -- shared across all pickups

return {
    OnCreate = function(entity)
        local _, y, _ = mota.getPosition(entity)
        baseY = y
        -- Tunable values come from Data/Tables/pickups.csv when present.
        spinSpeed    = mota.dataTableGetFloat("pickups", "coin", "spin", spinSpeed)
        pickupRadius = mota.dataTableGetFloat("pickups", "coin", "radius", pickupRadius)
    end,

    OnUpdate = function(entity, dt)
        t = t + dt

        -- Spin around Y and bob up and down.
        local half = t * spinSpeed * 0.5
        mota.setRotation(entity, 0.0, math.sin(half), 0.0, math.cos(half))
        local x, _, z = mota.getPosition(entity)
        local y = baseY + math.sin(t * 3.0) * 0.2
        mota.setPosition(entity, x, y, z)

        -- Collect when the player is close.
        if playerEntity and mota.isAlive(playerEntity) then
            local px, py, pz = mota.getPosition(playerEntity)
            if mota.distance(x, y, z, px, py, pz) < pickupRadius then
                mota.playSound3D("projects/MyGame/Audio/coin.wav", x, y, z, 0.8)
                mota.destroyEntity(entity)
            end
        end
    end,

    OnDestroy = function(entity)
        pickupsCollected = pickupsCollected + 1
        mota.log("pickups collected: " .. pickupsCollected)
    end,
}

Function index

FunctionGroup
mota.log(message)Logging
mota.createEntity() -> entityEntities
mota.isAlive(entity) -> booleanEntities
mota.destroyEntity(entity)Entities
mota.getPosition(entity) -> x, y, zTransforms
mota.setPosition(entity, x, y, z)Transforms
mota.getRotation(entity) -> x, y, z, wTransforms
mota.setRotation(entity, x, y, z, w)Transforms
mota.getScale(entity) -> x, y, zTransforms
mota.setScale(entity, x, y, z)Transforms
mota.raycast(ox, oy, oz, dx, dy, dz [, maxDistance]) -> hit, x, y, z, distancePhysics
mota.getBody(entity) -> bodyID or nilPhysics
mota.addForce(bodyID, fx, fy, fz)Physics
mota.addImpulse(bodyID, ix, iy, iz)Physics
mota.getVelocity(bodyID) -> vx, vy, vzPhysics
mota.setVelocity(bodyID, vx, vy, vz)Physics
mota.isActionPressed(action) -> booleanInput
mota.isKeyDown(action) -> booleanInput
mota.getAxis(axis) -> numberInput
mota.findEntity(name) -> entity or nilFinding entities
mota.findEntities(prefix) -> tableFinding entities
mota.getName(entity) -> string or nilFinding entities
mota.getParam(entity, key [, default]) -> valueFinding entities
mota.setCamera(ex, ey, ez, tx, ty, tz [, fov])Camera, HUD and appearance
mota.releaseCamera()Camera, HUD and appearance
mota.hudText(text) / mota.hudStatus(text)Camera, HUD and appearance
mota.settingsMenu() / mota.settingsRows(spec) / mota.lookSensitivity() / mota.invertLook()Settings menu
mota.voiceMenu()Voice chat
mota.voiceEnable(on) / mota.voiceEnabled()Voice chat
mota.voiceMode(mode) / mota.voiceTalk(held) / mota.voiceChannels(channels)Voice chat
mota.voiceMute(id [, muted]) / mota.voiceMuted(id)Voice chat
mota.voiceTalking([id]) / mota.voiceTransmitting() / mota.voiceName(id, name)Voice chat
mota.voicePlayer(connection, id, team) / mota.voicePosition(connection, x, y, z)Voice chat
mota.hudHealth(fraction) / mota.hudScore(n) / mota.hudScoreLabel(label)Camera, HUD and appearance
mota.hudShow(element, visible)Camera, HUD and appearance
mota.setColor(entity, r, g, b [, a]) / mota.setEmissive(entity, r, g, b) / mota.setVisible(entity, visible)Camera, HUD and appearance
mota.loadScene(path) -> boolean / mota.quit()Scenes and game flow
mota.playSequence(path [, loop]) -> boolean / mota.stopSequence(path)Scenes and game flow
mota.spawn(prefab, x, y, z [, yaw]) -> entity or nilScenes and game flow
mota.saveNumber(key, value) / mota.loadNumber(key [, default])Scenes and game flow
mota.exec(command) -> stringScenes and game flow
mota.defineMenu(name, spec)Menus and pause
mota.showMenu(name) / mota.pushMenu(name) / mota.popMenu() / mota.hideMenus()Menus and pause
mota.setPaused(paused) / mota.isPaused() -> booleanMenus and pause
mota.setFullscreen(on) / mota.isFullscreen() -> booleanMenus and pause
mota.mousePosition() -> x, y / mota.mouseToWorld([planeY]) -> hit, x, y, zMouse
mota.hudBanner(text [, seconds])Camera, HUD and appearance
mota.playSound(path [, volume]) -> booleanAudio
mota.playSound3D(path, x, y, z [, volume]) -> booleanAudio
mota.playMusic(path [, volume]) -> boolean / mota.stopMusic()Audio
mota.setVolume(bus, volume) / mota.getVolume(bus) -> numberAudio
mota.distance(x1, y1, z1, x2, y2, z2) -> numberMath
mota.normalize(x, y, z) -> x, y, zMath
mota.lerp(a, b, t) -> numberMath
mota.randomRange(min, max) -> numberMath
mota.getTime() -> numberTime
mota.dataTableHas(table) -> booleanData tables
mota.dataTableGetFloat(table, row, column [, default]) -> numberData tables
mota.dataTableGetInt(table, row, column [, default]) -> integerData tables
mota.dataTableGetBool(table, row, column [, default]) -> booleanData tables
mota.dataTableGetString(table, row, column [, default]) -> stringData tables
mota.experimentVariant(name [, default]) -> stringExperiments