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
| Object | Type | Purpose | Doc |
|---|---|---|---|
be | Engine Binding | Core engine access, physics, objects, vehicles | be.md |
extensions | Module | Extension loading and hook management | extensions.md |
guihooks | Module | UI communication bridge | guihooks.md |
map | Module | Level/map data and navigation | map.md |
scenetree | Engine Binding | Scene graph entity queries | scenetree.md |
Core Environment Globals
System Constants
| Global | Type | Description |
|---|---|---|
vmType | string | Always "game" in GE context. Identifies the Lua VM type. |
shipping_build | boolean | Release flag. true in public builds, false in development. (C++ binding) |
Logging Functions
| Global | Signature | Description |
|---|---|---|
print(...) | ... → nil | Console output. Wraps log('A', 'print', ...). |
log(level, tag, message) | string, string, string → nil | Structured 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 levelOther Globals
| Global | Type | Description |
|---|---|---|
worldReadyState | number | Level loading state: -1=no level, 0=loading, 1=materials, 2=ready |
photoModeOpen | boolean | Whether photo mode is open |
levelLoaded | any | Current loaded level info |
sailingTheHighSeas | boolean | Piracy 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 vehiclesObject 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()
endTime 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
endVehicle 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 MFull 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
| Event | Data | Purpose |
|---|---|---|
MenuOpenModule | moduleName | Open UI module |
MenuHide | nil | Hide menu |
ChangeState | {state = 'menu'} | Change game state |
ScenarioRewinded | nil | Reset 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()
endFull Reference: scenetree.md
System Modules
Core Gameplay Systems
Loaded via extensions.load('gameplay/<name>'):
| Module | Global | Description |
|---|---|---|
gameplay_missions_missions | gameplay_missions_missions | Mission data and loading |
gameplay_missions_missionManager | gameplay_missions_missionManager | Mission start/stop/foreground |
gameplay_missions_progress | gameplay_missions_progress | Mission progress tracking |
gameplay_traffic | gameplay_traffic | AI traffic management |
gameplay_parking | gameplay_parking | Parking challenges |
Career System
Access via: extensions.load('career/career')
| Module | Path | Description |
|---|---|---|
career_career | career/career | Career main module |
career_modules_playerAttributes | career/modules/playerAttributes | Money, XP, attributes |
career_modules_payment | career/modules/payment | Pay/canPay functions |
career_modules_inventory | career/modules/inventory | Vehicle inventory |
career_modules_insurance_insurance | career/modules/insurance/insurance | Vehicle insurance |
career_saveSystem | career/saveSystem | Save/load system |
Core Extensions
| Module | Global | Description |
|---|---|---|
core_settings_settings | core_settings_settings | Game settings (aliased as settings global) |
core_settings_graphic | core_settings_graphic | Graphics settings |
core_input_actionFilter | core_input_actionFilter | Input filtering |
core_gamestate | core_gamestate | Game state management |
core_camera | core_camera | Camera system |
core_groundMarkers | core_groundMarkers | Ground marker arrows |
Engine Lifecycle Hooks
GE provides hooks that extensions can implement for lifecycle events:
| Hook | Timing | Use Case |
|---|---|---|
onExtensionLoaded | Extension load (no args on self, name on others) | Setup, react to deps |
onInit | After batch extensions loaded (GE only) | Second-phase init |
onFirstUpdate | First GFX frame | Deferred heavy setup |
onUiReady | CEF UI fully loaded | UI-dependent logic |
onClientPreStartMission(levelPath) | Before mission resources load | Early level setup |
onClientPostStartMission(levelPath) | Level Lua loaded, objects available | Mission 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 spawn | Track vehicles |
onVehicleDestroyed(vid) | Vehicle removed | Cleanup vehicle data |
onVehicleResetted(vehicleID) | Vehicle reset | React to vehicle reset |
onVehicleSwitched(oldId, newId, player) | Player switches vehicle | Track player vehicle |
onResetGameplay(playerID) | Gameplay reset | Clean state |
onClientEndMission(levelPath) | Leaving level (hookNotify) | Level cleanup |
onFilesChanged(files) | File hot-reload | React to file changes |
onPreExit | Before shutdown | Save data |
onExit | Game shutting down | Final 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 levelTable 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 pathMath 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:
| From | To | Method | Syntax |
|---|---|---|---|
| GE | VE | C++ Bridge | veh:queueLuaCommand("code") |
| GE | All VEs | Broadcast | be:queueAllObjectLua("code") |
| VE | GE | C++ Bridge | obj:queueGameEngineLua("code") |
| GE | UI | Event | guihooks.trigger("event", data) |
| GE | UI | Stream | guihooks.queueStream("key", value) |
| GE | GE | Extension Hook | extensions.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...
endSafe Object Access
-- Always check if object exists
local veh = be:getPlayerVehicle(0)
if veh then
local pos = veh:getPosition()
-- Use pos...
endState + 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 MSoft 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
endType Reference
Common Engine Types
| Type | Description | Example |
|---|---|---|
Point3F | 3D position/vector | Point3F(1, 2, 3) |
Point2F | 2D position/vector | Point2F(1, 2) |
QuatF | Quaternion rotation | QuatF(0, 0, 0, 1) |
ColorF | RGBA color (0-1) | ColorF(1, 0, 0, 1) |
TransformF | Position + rotation | TransformF(pos, rot) |
MatrixF | 4x4 transform matrix | obj: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')")
endQuick 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 suffixCore Extensions Reference
| Extension | Purpose | Key Functions |
|---|---|---|
core_camera | Camera system | core_camera.setByName(0, "orbit"), core_camera.setFOV(0, 60) |
core_gamestate | Game state | core_gamestate.setGameState(...), core_gamestate.state |
core_settings_settings | Settings (aliased as settings) | settings.getValue(key), settings.setValue(key, val) |
core_input_actionFilter | Input filtering | core_input_actionFilter.addAction(0, action) |
core_environment | Weather/Time/Gravity | core_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