RLS Studios
ProjectsPatreonCommunityDocsAbout
Join Patreon
BeamNG Modding Docs

Guides

Reference

`be` - BeamNG Engine BindingGlobal Utility Functions CatalogGE Global Objects & FunctionsGE Object Path LookupSceneTree - Scene Graph Queries

UI

Resources

BeamNG Game Engine Lua Cheat SheetGE Developer RecipesMCP Server Setup

// RLS.STUDIOS=true

Premium Mods for BeamNG.drive. Career systems, custom vehicles, and immersive gameplay experiences.

Index

HomeProjectsPatreon

Socials

DiscordPatreon (RLS)Patreon (Vehicles)

© 2026 RLS Studios. All rights reserved.

Modding since 2024

API Referenceglobals

GE Global Objects & Functions

Complete reference for global variables, objects, and functions available in the BeamNG Game Engine (GE) Lua context.

Complete reference for global variables, objects, and functions available in the BeamNG Game Engine (GE) Lua context.


Global Objects Overview

ObjectTypePurposeDoc
beEngine BindingCore engine access, physics, objects, vehiclesbe.md
extensionsModuleExtension loading and hook managementextensions.md
guihooksModuleUI communication bridgeguihooks.md
mapModuleLevel/map data and navigationmap.md
scenetreeEngine BindingScene graph entity queriesscenetree.md

Core Environment Globals

System Constants

GlobalTypeDescription
vmTypestringAlways "game" in GE context. Identifies the Lua VM type.
shipping_buildbooleanRelease flag. true in public builds, false in development. (C++ binding)

Logging Functions

GlobalSignatureDescription
print(...)... → nilConsole output. Wraps log('A', 'print', ...).
log(level, tag, message)string, string, string → nilStructured logging. Wraps C++ Lua:log().

Log Levels: 'D' (Debug), 'I' (Info), 'W' (Warning), 'E' (Error), 'A' (Always)

log('I', 'myMod', 'Info message')   -- Info level
log('W', 'myMod', 'Warning!')       -- Warning level
log('E', 'myMod', 'Error!')         -- Error level
log('D', 'myMod', 'Debug data')     -- Debug level

Other Globals

GlobalTypeDescription
worldReadyStatenumberLevel loading state: -1=no level, 0=loading, 1=materials, 2=ready
photoModeOpenbooleanWhether photo mode is open
levelLoadedanyCurrent loaded level info
sailingTheHighSeasbooleanPiracy detection flag

be - BeamNG Engine

Core engine interface for physics, vehicles, objects, and world state.

Vehicle Access

-- Get player vehicle (0 = first player)
local veh = be:getPlayerVehicle(0)

-- Get vehicle by ID
local veh = be:getObjectByID(vehID)

-- Get all vehicles
local vehicles = be:getObject(0)  -- Group object containing vehicles

Object Queries

-- Find object by name (use scenetree, not be)
local obj = scenetree.findObject("myObject")

-- Get object count
local count = be:getObjectCount()

-- Get object by index
local obj = be:getObject(0)

Physics Control

-- Pause/resume via simTimeAuthority
simTimeAuthority.pause(true)   -- Pause
simTimeAuthority.pause(false)  -- Resume

-- Time scale (slow motion)
be:setPhysicsSpeedFactor(0.5)  -- Half speed
be:setPhysicsSpeedFactor(1.0)  -- Normal

-- Start/stop physics simulation
be:physicsStartSimulation()
be:physicsStopSimulation()

Vehicle Spawning & Destruction

-- Spawn vehicle (use the spawn module, not be directly)
local veh = spawn.spawnVehicle("etk800", "vehicles/etk800/default.pc", vec3(0,0,100), quat(0,0,0,1))

-- Enter/switch to a vehicle
be:enterVehicle(0, veh)  -- playerIndex, vehicleObj

-- Remove a vehicle
veh:delete()

-- Delete all vehicles (iterate backwards)
for i = be:getObjectCount() - 1, 0, -1 do
    be:getObject(i):delete()
end

Time of Day

-- Time of day is controlled via core_environment, not be directly
core_environment.setTimeOfDay({time = 0.5})  -- 0.0-1.0 (0.5 = noon)

-- Or via scenetree TimeOfDay object
local tod = scenetree.findObject("TimeOfDay")
if tod then
    tod.time = 0.5
    tod.play = false  -- Stop day/night cycle
end

Vehicle Communication

-- Send Lua command to vehicle's VE context
local veh = be:getObjectByID(vehID)
if veh then
    veh:queueLuaCommand("electrics.values.hazard = 1")
end

-- Send command to all vehicles
be:queueAllObjectLua("obj:setGravity(-9.81)")

Full Reference: be.md


extensions - Extension System

Manages modular extensions and hook chains.

Loading Extensions

-- Load extension by name (from lua/ge/extensions/)
extensions.load('myExtension')
extensions.load('gameplay/missions/myMission')

-- Unload extension
extensions.unload('myExtension')

-- Reload (hot-reload during development)
extensions.reload('myExtension')

-- Check if loaded
local loaded = extensions.isExtensionLoaded('myExtension')

-- Get list of loaded extensions
local loadedExts = extensions.getLoadedExtensionsNames()

Hook System

-- Trigger a hook (calls all registered handlers)
extensions.hook('onResetGameplay', playerID)
extensions.hook('onVehicleSpawned', vehID)

-- Trigger hook with notification (processes fresh-loaded extensions immediately)
extensions.hookNotify('onClientStartMission', levelPath)

Extension Module Structure

local M = {}

-- Optional: Declare dependencies
M.dependencies = {'core_settings_settings', 'gameplay_sites_sitesManager'}

-- Lifecycle hooks
function M.onExtensionLoaded()
    -- Called when this extension loads
end

function M.onUpdate(dtReal, dtSim, dtRaw)
    -- Called every frame, before physics
end

function M.onPreRender(dtReal, dtSim, dtRaw)
    -- Called every frame, after physics, before render
end

function M.onClientPostStartMission(levelPath)
    -- Called when level Lua loaded, scene objects available
end

function M.onVehicleSpawned(vid, vehObj)
    -- Called when vehicle spawns
end

function M.onVehicleDestroyed(vid)
    -- Called when vehicle is destroyed
end

return M

Full Reference: extensions.md


guihooks - UI Communication

Bridge between GE Lua and the Chromium UI (CEF).

Triggering UI Events

-- Send event to UI (one-way)
guihooks.trigger('EventName', data)

-- Examples
guihooks.trigger('MenuOpenModule', 'vehicleselect')
guihooks.trigger('MissionStateChanged', {active = true})
guihooks.trigger('Notification', {
    type = 'info',
    title = 'Hello',
    message = 'World'
})

Streaming Data to UI

-- Queue data for streaming (high frequency updates)
guihooks.queueStream('key', value)

-- Send all queued streams
guihooks.sendStreams()

-- Immediate stream transmission
guihooks.triggerStream('streamName', streamData)

-- Send to specific UI target
guihooks.triggerClient(targetDsmId, 'EventName', data)

-- Simple message popup
guihooks.message("Hello!", 5, "info")

Common UI Events

EventDataPurpose
MenuOpenModulemoduleNameOpen UI module
MenuHidenilHide menu
ChangeState{state = 'menu'}Change game state
ScenarioRewindednilReset scenario UI state
Notification{type, title, message}Show notification
UpdateMissionProgress{id, progress}Update mission UI
toastrMsg{type, title, msg}Toast notification

Full Reference: guihooks.md


map - Level & Navigation

Map and level data access.

-- Get current level data
local levelData = map.getMap()

-- Access map nodes (road network)
local nodes = levelData.nodes
local node = nodes[nodeName]

-- Node properties
local pos = node.pos        -- Point3F position
local links = node.links    -- Connected nodes

-- Find closest road to position
local road = map.findClosestRoad(pos)

-- Force map load (usually automatic)
map.assureLoad()

Full Reference: map.md


scenetree - Scene Graph

Query and manipulate scene objects.

-- Find object by name
local obj = scenetree.findObject("objectName")

-- Find object by ID
local obj = scenetree.findObjectById(id)

-- Find all objects of a class
local ids = scenetree.findClassObjects("PointLight")

-- Direct access to well-known objects
scenetree.tod.play = false  -- Stop time-of-day cycle

-- Common object operations
if obj then
    -- Get transform
    local pos = obj:getPosition()
    local rot = obj:getRotation()
    
    -- Set transform
    obj:setPosition(pos)
    obj:setRotation(rot)
    
    -- Visibility
    obj:setHidden(true)
    obj:setHidden(false)
    
    -- Get class name
    local className = obj:getClassName()
    
    -- Delete object
    obj:delete()
end

Full Reference: scenetree.md


System Modules

Core Gameplay Systems

Loaded via extensions.load('gameplay/<name>'):

ModuleGlobalDescription
gameplay_missions_missionsgameplay_missions_missionsMission data and loading
gameplay_missions_missionManagergameplay_missions_missionManagerMission start/stop/foreground
gameplay_missions_progressgameplay_missions_progressMission progress tracking
gameplay_trafficgameplay_trafficAI traffic management
gameplay_parkinggameplay_parkingParking challenges

Career System

Access via: extensions.load('career/career')

ModulePathDescription
career_careercareer/careerCareer main module
career_modules_playerAttributescareer/modules/playerAttributesMoney, XP, attributes
career_modules_paymentcareer/modules/paymentPay/canPay functions
career_modules_inventorycareer/modules/inventoryVehicle inventory
career_modules_insurance_insurancecareer/modules/insurance/insuranceVehicle insurance
career_saveSystemcareer/saveSystemSave/load system

Core Extensions

ModuleGlobalDescription
core_settings_settingscore_settings_settingsGame settings (aliased as settings global)
core_settings_graphiccore_settings_graphicGraphics settings
core_input_actionFiltercore_input_actionFilterInput filtering
core_gamestatecore_gamestateGame state management
core_cameracore_cameraCamera system
core_groundMarkerscore_groundMarkersGround marker arrows

Engine Lifecycle Hooks

GE provides hooks that extensions can implement for lifecycle events:

HookTimingUse Case
onExtensionLoadedExtension load (no args on self, name on others)Setup, react to deps
onInitAfter batch extensions loaded (GE only)Second-phase init
onFirstUpdateFirst GFX frameDeferred heavy setup
onUiReadyCEF UI fully loadedUI-dependent logic
onClientPreStartMission(levelPath)Before mission resources loadEarly level setup
onClientPostStartMission(levelPath)Level Lua loaded, objects availableMission logic
onClientStartMission(levelPath)Level items loaded (hookNotify)Level setup
onWorldReadyState(state)World ready (2=fully loaded)Post-spawn setup
onUpdate(dtReal, dtSim, dtRaw)Every frame (before physics)Game logic, timers
onPreRender(dtReal, dtSim, dtRaw)Every frame (after physics)Visual updates
onGuiUpdate(dtReal, dtSim, dtRaw)Every frame (UI updates)UI-specific per-frame
onVehicleSpawned(vid, vehObj)Vehicle spawnTrack vehicles
onVehicleDestroyed(vid)Vehicle removedCleanup vehicle data
onVehicleResetted(vehicleID)Vehicle resetReact to vehicle reset
onVehicleSwitched(oldId, newId, player)Player switches vehicleTrack player vehicle
onResetGameplay(playerID)Gameplay resetClean state
onClientEndMission(levelPath)Leaving level (hookNotify)Level cleanup
onFilesChanged(files)File hot-reloadReact to file changes
onPreExitBefore shutdownSave data
onExitGame shutting downFinal cleanup

Full Reference: initSequence.md, TL;DR Architect


Global Functions

JSON Serialization

-- Encode table to JSON string
local jsonStr = jsonEncode({key = "value", num = 42})
-- Result: {"key":"value","num":42}

-- Decode JSON string to table
local data = jsonDecode('{"key": "value"}')
print(data.key)  -- "value"

-- Pretty print (with indentation)
local pretty = jsonEncodePretty({a = 1, b = 2})

Logging

-- Structured logging
log('I', 'myMod', 'Info message')   -- Info level
log('W', 'myMod', 'Warning!')       -- Warning level
log('E', 'myMod', 'Error!')         -- Error level
log('D', 'myMod', 'Debug data')     -- Debug level

Table Utilities

-- Deep copy a table
local copy = deepcopy(original)

-- Shallow clone
local clone = shallowcopy(original)

-- Dump table to string (debugging)
local str = dump(myTable)
print(dump(myTable))

-- Print table recursively
rdump(myTable, "prefix")

-- Check if table is empty
local empty = tableIsEmpty(tbl)

-- Get table size (for non-array tables)
local size = tableSize(tbl)

-- Clear table
table.clear(tbl)

-- Find key in table
local key = tableFind(tbl, value)

-- Merge tables
local merged = tableMerge(tbl1, tbl2)

Math Helpers

-- Clamp value
local value = clamp(x, min, max)

-- Linear interpolation
local value = lerp(a, b, t)

-- Smooth step (takes single 0-1 value)
local value = smoothstep(x)

-- Sign function
local s = sign(x)  -- -1, 0, or 1

-- Round number
local r = round(x)         -- Nearest integer
local r = roundNear(x, 0.01)  -- Round to nearest 0.01

-- Square
local sq = square(x)

-- Degrees/radians conversion
local rad = math.rad(deg)
local deg = math.deg(rad)

String Functions

-- Split string (global function)
local parts = split("a,b,c", ",")  -- {"a", "b", "c"}

-- Also available as string method (regex delimiter)
local parts = string.split("a,b,c", ",")

-- Trim whitespace (global function)
local trimmed = trim("  hello  ")  -- "hello"

-- String starts/ends with
local yes = string.startswith("hello", "he")   -- true
local yes = string.endswith("hello", "lo")     -- true

-- Formatting
local formatted = string.format("Value: %.2f", 3.14159)

Type Checking

-- Standard Lua type checking
local isTbl = type(value) == "table"
local isNum = type(value) == "number"
local isStr = type(value) == "string"
local isFunc = type(value) == "function"

File System

-- Read file to string (global)
local content = readFile("/path/to/file.txt")

-- Write file (global)
writeFile("/path/to/file.txt", content)

-- Filesystem operations (C++ FS binding)
FS:fileExists("path/to/file.txt")
FS:directoryExists("path/to/dir/")
FS:directoryCreate("path/to/dir/")
FS:findFiles("dir/", "*.lua", -1, true, false)  -- dir, pattern, depth, files, dirs
FS:getFileRealPath("path")  -- Resolve VFS path to disk path

Math Types

-- vec3 (aliased as Point3F)
local v = vec3(x, y, z)
local dist = v:distance(other)
local len = v:length()
local norm = v:normalized()
local dot = v:dot(other)
local cross = v:cross(other)

-- quat / QuatF rotations
local q = quat(x, y, z, w)
local q2 = quatFromEuler(rx, ry, rz)  -- global function

-- Point2F (2D vector)
local point2d = Point2F(x, y)

-- ColorF (RGBA 0-1)
local color = ColorF(r, g, b, a)

Inter-VM Communication

GE can communicate with Vehicle Engines (VE) and the UI:

FromToMethodSyntax
GEVEC++ Bridgeveh:queueLuaCommand("code")
GEAll VEsBroadcastbe:queueAllObjectLua("code")
VEGEC++ Bridgeobj:queueGameEngineLua("code")
GEUIEventguihooks.trigger("event", data)
GEUIStreamguihooks.queueStream("key", value)
GEGEExtension Hookextensions.hook("event", ...)

GE → VE Communication Example

-- Send command to vehicle
local veh = be:getPlayerVehicle(0)
if veh then
    veh:queueLuaCommand("electrics.setLightsState(2)")
end

-- Send data via JSON
local data = jsonEncode({speed = 50})
veh:queueLuaCommand("myMod.receiveData('" .. data .. "')")

VE → GE Communication Example

-- From vehicle Lua (VE context)
obj:queueGameEngineLua("extensions.hook('onVehicleEvent', " .. obj:getId() .. ")")

Full Reference: communication.md


Common Patterns

Vehicle Iteration

-- Iterate all vehicles (be manages the object pool directly)
for i = 0, be:getObjectCount() - 1 do
    local veh = be:getObject(i)
    local vehID = veh:getID()
    -- Process vehicle...
end

Safe Object Access

-- Always check if object exists
local veh = be:getPlayerVehicle(0)
if veh then
    local pos = veh:getPosition()
    -- Use pos...
end

State + UI Sync

-- Update state
myMod.state.active = true

-- Persist if needed
myMod.saveState()

-- Sync UI (no ghost values!)
guihooks.trigger('MyModStateChanged', myMod.state)

Extension Hook Handler

local M = {}

-- Track vehicles
local vehicles = {}

function M.onVehicleSpawned(vid, vehObj)
    vehicles[vid] = {
        spawnTime = os.clock()
    }
end

function M.onVehicleDestroyed(vid)
    vehicles[vid] = nil
end

function M.onResetGameplay(playerID)
    table.clear(vehicles)
end

return M

Soft Dependency Pattern

-- Check at runtime if optional extension is available
function M.someFunction()
    if optionalMod and optionalMod.doSomething then
        optionalMod.doSomething()
    else
        -- Fallback behavior
    end
end

Type Reference

Common Engine Types

TypeDescriptionExample
Point3F3D position/vectorPoint3F(1, 2, 3)
Point2F2D position/vectorPoint2F(1, 2)
QuatFQuaternion rotationQuatF(0, 0, 0, 1)
ColorFRGBA color (0-1)ColorF(1, 0, 0, 1)
TransformFPosition + rotationTransformF(pos, rot)
MatrixF4x4 transform matrixobj:getTransform()

Vehicle Object Methods

local veh = be:getPlayerVehicle(0)
if veh then
    -- ID and name
    local id = veh:getID()
    local name = veh:getName()
    local jbeam = veh:getJBeamFilename()
    
    -- Transform
    local pos = veh:getPosition()
    local rot = veh:getRotation()
    local vel = veh:getVelocity()
    local angVel = veh:getAngularVelocity()
    
    -- State
    local active = veh:isActive()
    local visible = not veh:isHidden()
    
    -- Control
    veh:setPositionRotation(x, y, z, rx, ry, rz, rw)
    veh:reset()  -- Reset to spawn position
    veh:delete()  -- Remove vehicle
    
    -- Communication
    veh:queueLuaCommand("print('hello from GE')")
end

Quick Reference: Most Used Globals

-- Vehicle Access
be:getPlayerVehicle(0)               -- Get player vehicle object
be:getObjectByID(id)                 -- Get vehicle by ID (also global getObjectByID)
be:getObjectCount()                  -- Number of managed objects
be:enterVehicle(0, veh)              -- Switch player to vehicle

-- Level/Scene
map.getMap()                         -- Current level data
map.getMapName()                     -- Level name
scenetree.findObject("name")         -- Find entity by name
scenetree.findObjectById(id)         -- Find entity by ID

-- Extensions
extensions.load('name')              -- Load extension
extensions.unload('name')            -- Unload extension
extensions.hook('onResetGameplay', playerID)  -- Trigger hook
extensions.isExtensionLoaded('name') -- Check if extension loaded

-- UI Communication
guihooks.trigger('Event', data)      -- Send event to UI
guihooks.queueStream('key', value)   -- Stream data to UI
guihooks.sendStreams()               -- Flush queued streams
reloadUI()                           -- Force UI reload

-- JSON
jsonEncode({data = true})            -- Serialize to JSON
jsonDecode('{"key": "value"}')      -- Parse JSON
jsonEncodePretty(tbl)                -- Pretty-print JSON

-- Logging
log('I', 'mod', 'message')           -- Log info message
print("message")                     -- Print to console

-- Utilities
dumps(table)                         -- Debug dump to string
deepcopy(original)                   -- Deep copy table
shallowcopy(original)                -- Shallow copy table
clamp(x, min, max)                   -- Clamp value
lerp(a, b, t)                        -- Linear interpolation
round(x)                             -- Round to nearest integer
roundNear(x, m)                      -- Round to nearest m
sign(x)                              -- Sign of number
split(str, delimiter)                -- Split string
trim(str)                            -- Trim whitespace
string.startswith(str, prefix)       -- Check prefix
string.endswith(str, suffix)         -- Check suffix

Core Extensions Reference

ExtensionPurposeKey Functions
core_cameraCamera systemcore_camera.setByName(0, "orbit"), core_camera.setFOV(0, 60)
core_gamestateGame statecore_gamestate.setGameState(...), core_gamestate.state
core_settings_settingsSettings (aliased as settings)settings.getValue(key), settings.setValue(key, val)
core_input_actionFilterInput filteringcore_input_actionFilter.addAction(0, action)
core_environmentWeather/Time/Gravitycore_environment.setTimeOfDay({time=0.5}), core_environment.setGravity(-9.81)

Document version: GE 0.35+ | Tags: #core #globals #reference #ge #api


See Also

  • TL;DR Architect - Quick rules reference
  • Boot Sequence - Extension lifecycle and initialization
  • Communication Guide - Cross-context communication patterns
  • Property Tree - Quick lookup for GE object paths
  • Cheat Sheet - 50+ common one-liners
  • TAGS.md - Tagging system for discovery

Global Utility Functions Catalog

Functions available globally in both GE and VE contexts. Loaded from `lua/common/utils.lua` and `lua/common/luaCore.lua`.

GE Object Path Lookup

Quick lookup reference for BeamNG Game Engine (GE) object paths and extension names.

On this page

Global Objects OverviewCore Environment GlobalsSystem ConstantsLogging FunctionsOther Globalsbe - BeamNG EngineVehicle AccessObject QueriesPhysics ControlVehicle Spawning & DestructionTime of DayVehicle Communicationextensions - Extension SystemLoading ExtensionsHook SystemExtension Module Structureguihooks - UI CommunicationTriggering UI EventsStreaming Data to UICommon UI Eventsmap - Level & Navigationscenetree - Scene GraphSystem ModulesCore Gameplay SystemsCareer SystemCore ExtensionsEngine Lifecycle HooksGlobal FunctionsJSON SerializationLoggingTable UtilitiesMath HelpersString FunctionsType CheckingFile SystemMath TypesInter-VM CommunicationGE → VE Communication ExampleVE → GE Communication ExampleCommon PatternsVehicle IterationSafe Object AccessState + UI SyncExtension Hook HandlerSoft Dependency PatternType ReferenceCommon Engine TypesVehicle Object MethodsQuick Reference: Most Used GlobalsCore Extensions ReferenceSee Also