Lua:Reference

Lua:Reference

From BeamNG

We have two separate versions of Lua running: Vehicle Lua and GameEngine Lua. Both have different API, though some is shared. We'll try to explain thins here a bit.

It is split like this in the game folder:

  • lua (do not put things here)
    • common
      The folder for libraries/tools that are generic enough to be used for both libbeamng and gameengine.
    • console
      This is the instance directory for the console.exe / bananabench. Its a Lua only physics console that comes without the grapics/gameengine. Will execute main.lua on start.
      Restart of the process is required to reload changes on the lua files.
    • vehicle
      This is the vehicle instance directory. Every vehicle will spawn a new process by executing main.lua.
      It can be reloaded with the vehicle using CTRL + R
    • t3d / ge
      This is the Lua instance directory for the game engine. It will spawn a process using main.lua at the start of the engine.
      It can be reloaded while the engine is running via CTRL + L

We'll start to give an overview of the Game Engine Lua Functions:

Game Engine Lua

Generally available classes/objects/functions to be used:

Events

Events that automatically get called by the game engine.

Event Signature Example Description
void onRaceStart()
local function onRaceStart()
  print('onRaceStart')
end
This event gets called once the scenario countdown has run down. 
void onRaceTick(number raceTickTime)
local function onRaceTick(raceTickTime)
  print('onRaceTick')
end
This event gets called every quarter-second once the scenario is running. 

Environment

Function Signature Example Description
number getGravity()
environment.getGravity()
Returns the gravity of the current loaded level e.g. -9.81 
void setGravity(number grav)
environment.setGravity(-9.81)
Sets the gravity of the current loaded level
table getTimeOfDay()
environment.setTimeOfDay({time=1})

environment.setTimeOfDay({time=0.5, play=true})

environment.setTimeOfDay({dayScale=1, nightScale=1.5})
Returns a table with the following elements:
number dayLength
number dayScale
number nightScale
bool play
number time - actual time between ''0'' and ''1'' where ''0'' and ''1'' are noon (12pm) and 0.5 is midnight (12am) 
void setTimeOfDay()
environment.getTimeOfDay()
Sets values of the timeOfDay table accordingly to the values which were passed to the function

ColorI

Integer Color Class. Range from 0 to 255 for all fields

Function Signature Example Description
void ColorI(number red, number green, number blue, number alpha)
local red = 50
local green = 100
local blue = 137
local alpha = 255
local c = ColorI(red, green, blue, alpha)
print(c.r) -- returns 50
print(c.g) -- returns 100
print(c.b) -- returns 137
print(c.a) -- returns 255
Constructor, number values from 0 to 255.
Attribute Name Type Description
r number (0-255) Red Channel
g number (0-255) Green Channel
b number (0-255) Blue Channel
a number (0-255) Alpha Channel

Lua

Interface for the Lua instance. Can be accessed from GameEngine Lua only via Lua

Function Signature Example Description
nil Lua:log(char level, string origin, string msg)
Lua:log('D', 'myFile', 'I am a debug message')
log('I', 'myFile', 'Using the shortcut')
Central Logging function. You can use the shortcut log() instead.
nil Lua:blacklistLogLevel(string levels)
-- disables output of all Debug a Info level messages
Lua:blacklistLogLevel('DI')
Blacklists all named log levels on all channels (consoles, file).

This is handy when you want to disable all outputs from some levels.

nil Lua:exec(string filename)
Lua:exec('foo/bar/myfile.lua')
Executes a Lua file. Async, executed upon next frame.
nil Lua:dumpStack(char loglevel)
-- dumps the Lua stack in the log with log level Error
Lua:dumpStack('E')
Dumps the Lua stack into the logs
number Lua:getMemoryUsageKB()
print(Lua:getMemoryUsageKB())
Returns the memory usage in kilo Bytes
nil Lua:enableStackTraceFile(string filename, boolean full)
Lua:enableStackTraceFile("lua_stacktrace.txt", true)
enables the stack tracing functions
table Lua:saveObject(SimObject obj)
dump(Lua:saveObject(scenetree.myObject))
serializes the properties of a simobject into a table
bool Lua:findObjectByNameAsTable(string simObjectName, table resultTableReference)
returns a simobject -- do not use: internal function. Use scenetree.findObject() instead
number Lua:findObjectsByClassAsTable(string simObjectClassName, table resultTableReference)
returns simobjects -- do not use: internal function. Use scenetree.findClassObjects() instead
boolean Lua:castSimObject(ConsoleObject obj, table resultTableReference)
internal usage - use scenetree
table Lua:getSimobjectFieldList(ConsoleObject obj)
internal usage - use scenetree
BeamNGVehicle Lua:getControlVehicle()
returns the currently controlled vehicle
nil Lua:setControlVehicle(BeamNGVehicle vehicle, number playerID)
sets the vehicle to be controlled
string Lua:getSelectedLanguage()
returns the language chosen by the user
Attribute Name Type Description
Lua.lastDebugFocusPos Point3F
Lua.userLanguage string

BeamEngine

Function Signature Example Description
BeamNGVehicle be:getObject(number vehicleObjectID)

BeamNGVehicle be:getObjectByPhysicsID(number vehiclePhysicsID)

number be:getObjectCount()

BeamNGVehicle be:getPlayerVehicle(number playerID)

string be:getFFBConfig(number FFBId)

nil be:queueAllObjectLua(string lua)

nil be:queueSystemLua(string lua)

nil be:executeJS(string js)

nil be:executeStreamJS(string streamReference, string js)

boolean be:getEnabled()

nil be:zoom(number zoomValue, number playerID)

nil be:reloadVehicle(number playerID)

nil be:resetVehicle(number playerID)

nil be:toggleEnabled()

nil be:resetCam(number playerID)

nil be:camLookBack(number playerID)

nil be:exitVehicle(number playerID)

nil be:enterNextVehicle(number playerID, number step)

nil be:enterVehicle(number playerID, BeamNGVehicle vehicleInstance)

nil be:cameraToggle(number playerID)

nil be:reloadSystemLua()

nil be:reloadStaticCollision(boolean debug)

nil be:isBlockedByFirewall()

nil be:addFirewallException()

Attribute Name Type Description
BeamEngine.persistenceLuaData string
BeamEngine.nodeStream BeamNGNodeStreamPhysFS


TODO

things we still need to document properly, sorry for the chaos:

-- ActionMap
bindCmd - bool ActionMap::processBindCmd(const char *device, const char *action, const char *makeCmd, const char *breakCmd)
bindFull - bool ActionMap::processBindFull(const char* devName, const char* bindingAction, const char* control, bool isCentered, const F32 deadZoneBegin, const F32 deadZoneEnd, const F32 linearity, bool isInverted, bool isForceEnabled, bool isForceInverted, const char* ffbParams, bool actsOnChange, const char* onChange, bool actsOnDown, const char* onDown, bool actsOnUp, const char* onUp, const int filterType, const bool isRelative, const int player, const int commandContext)
unbindAllDevices - void ActionMap::processUnbindAllDevices() {
setActionProcessingEnabled - void setActionProcessingEnabled(bool enabled)

ActionMap_addToFilter - const int idx, const std::string &action, bool filtered
ActionMap_clearFilters - return table - const int idx

-- BeamFileSystem

BeamFileSystem:fileExists
-- bool fileExists( string filename )
-- Desc:
-- Params:
-- return: true if files exist in VFS

BeamFileSystem:openFile
-- TorqueFile openFile( string filename, string mode )
-- Desc: Open a file for read/write
-- Params:
  -- mode: use'r' for read, 'w' for write, 'a' or '+' for append
-- return: return TorqueFile object or nil on fail

BeamFileSystem:directoryExists
-- bool directoryExists( string directory )
-- Desc:
-- Params:
  -- directory: path need to end on '/' example:"path1/path2/path3/"
-- return: true if directory exist

BeamFileSystem:openDirectory
-- BeamNG::IDirectory openDirectory( string directory )
-- Desc:
-- Params:
  -- directory: path need to end on '/' example:"path1/path2/path3/"
-- return: directory object or nil on fail.

BeamFileSystem:closeDirectory
-- nil closeDirectory( BeamNG::IDirectory dir )
-- Desc:
-- Params:
  -- dir: A directory object already opened
-- return:

BeamFileSystem:findFilesByPattern
-- table[array] findFilesByPattern( string inBasePath, string inFilePattern, bool inRecursive, bool multiMatch, bool includeDirs)
-- Desc: Get all files matching in a path.
-- Params:
  -- inBasePath: path need to end on '/' example:"path1/path2/path3/"
  -- inFilePattern: pater
-- return: array of files/folders mathing the search and if includeDirs is set the folders than contain any of the entries. Folders have the prefix "DIR:"

BeamFileSystem:findFilesByRootPattern
-- table[array] findFilesByRootPattern(string _inBasePath, string inFilePattern, bool inRecursive, bool multiMatch, bool includeDirs)
-- Desc: As findFilesByPattern but all paths start with prefix "game:"
-- Params:
-- return:

BeamFileSystem:hashFile
-- string hashFile (string filename)
-- Desc: Hash the content of a file
-- Params:
  -- filename: path the the file
-- return: hash string

BeamFileSystem:getLastError
-- string getLastError()
-- Desc: Return the last error in the file system
-- return: error msg

BeamFileSystem:stat
-- table stat(string filename)
-- Desc: Get details about a file
-- Params:
  -- filename: path the the file
-- return: table include: { "filesize" = number, "modtime" = number, "createtime" = number, "accesstime" = number, "readonly" = bool, "filetype" = string ( "file"/"dir"/"link"/"other" ) }

BeamFileSystem:removeFile
-- bool removeFile (string filepath)
-- Desc: Delete a file from the file system
-- Params:
  -- filename: path the the file
-- return: true if file is deleted, false on fail.

BeamFileSystem:renameFile
-- bool renameFile (string from, string to)
-- Desc: Rename a file in the file system
-- Params:
-- return: true if the file is renamed, false on fail

BeamFileSystem:mount
-- bool mount(string srcPath, string mountPath, number priority)
-- Desc: mount a folder or ZIP in the virtual filesystem.
-- Params:
  -- srcPath: path the the folder/ZIP
  -- mountPath: path whe the folder/ZIP are mounted in the VFS.
  -- priority: order of search for files in VFS. use 0 for mods.
-- return:

BeamFileSystem:mountList
-- bool mountList( table[array] entries ) - params: 
-- Desc:
-- Params:
  -- enties: each entry = { "srcPath" = string, "mountPath" = string, "priority" = number }
-- return:

BeamFileSystem:unmount - bool unmount(string path) - unmount a folder or ZIP.
-- Desc:
-- Params:
-- return:

BeamFileSystem:isMounted - bool isMounted(string path) - return: true if a path is mounted
-- Desc:
-- Params:
-- return:

--ZipArchive

BeamFileSystem:openArchiveName - const char *filename, const char *mode
-- Desc:
-- Params:
-- return:

BeamFileSystem:getFileList
-- Desc:
-- Params:
-- return:

BeamFileSystem:readFileEntryByIdx
-- Desc:
-- Params:
-- return:

BeamFileSystem:getFileEntryHashByIdx
-- Desc:
-- Params:
-- return:

BeamFileSystem:addFile
-- Desc:
-- Params:
-- return:

BeamFileSystem:extractFile
-- Desc:
-- Params:
-- return:

BeamFileSystem:deleteFile
-- Desc:
-- Params:
-- return:

BeamFileSystem:close
-- Desc:
-- Params:
-- return:

-- WinInput
updateForceFeedback
sendJavaScriptHardwareInfo
getRegisteredDevices
getProductGUID
getProductName
getVendorIDProductID
getFeaturesString

-- timer
timer:reset
-- Desc:
-- Params:
-- return:

timer:stop
-- Desc:
-- Params:
-- return:

timer:triggered
-- Desc:
-- Params:
-- return:

timer:stopAndReset
-- Desc:
-- Params:
-- return:

timer:getTime
-- Desc:
-- Params:
-- return:

-- hptimer
hptimer:reset
-- Desc:
-- Params:
-- return:

hptimer:stop
-- Desc:
-- Params:
-- return:

hptimer:triggered
-- Desc:
-- Params:
-- return:

hptimer:stopAndReset
-- Desc:
-- Params:
-- return:

hptimer:getTime
-- Desc:
-- Params:
-- return:

-- FSDirectory
FSDirectory:getNextFilename
-- Desc:
-- Params:
-- return:


-- ColorF
constructor - float, float, float, float
-- Desc:
-- Params:
-- return:

-- Point2F
constructor - float, float
-- Desc:
-- Params:
-- return:

-- Point3F
constructor - float, float, float
-- Desc:
-- Params:
-- return:

len
-- Desc:
-- Params:
-- return:

neg
-- Desc:
-- Params:
-- return:

lenSquared
-- Desc:
-- Params:
-- return:

asPoint2D
-- Desc:
-- Params:
-- return:

set
-- Desc:
-- Params:
-- return:

setAll
-- Desc:
-- Params:
-- return:

zero
-- Desc:
-- Params:
-- return:

normalize
-- Desc:
-- Params:
-- return:

normalizeSafe
-- Desc:
-- Params:
-- return:

-- String
c_str
-- Desc:
-- Params:
-- return:


-- ConsoleObject

-- SimObject
delete
-- Desc:
-- Params:
-- return:

getField
-- Desc:
-- Params:
-- return:

setField
-- Desc:
-- Params:
-- return:

getDeclarationLine
-- Desc:
-- Params:
-- return:

setDeclarationLine
-- Desc:
-- Params:
-- return:

setStaticDataFieldbyIndex
-- Desc:
-- Params:
-- return:

getStaticDataFieldbyIndex
-- Desc:
-- Params:
-- return:

getDynDataFieldbyName
-- Desc:
-- Params:
-- return:

setDynDataFieldbyName
-- Desc:
-- Params:
-- return:

postApply
-- Desc:
-- Params:
-- return:

isChildOfGroup
-- Desc:
-- Params:
-- return:


-- NetObject

-- SceneObject
setHidden
-- Desc:
-- Params:
-- return:

isHidden
-- Desc:
-- Params:
-- return:

setPosition
-- Desc:
-- Params:
-- return:

getPosition
-- Desc:
-- Params:
-- return:

getScale
-- Desc:
-- Params:
-- return:

setScale
-- Desc:
-- Params:
-- return:


-- GameBase
-- ShapeBase
-- MissionMarker

-- SimSet
addObject
-- Desc:
-- Params:
-- return:

removeObject
-- Desc:
-- Params:
-- return:


-- SimGroup
removeObject
-- Desc:
-- Params:
-- return:

findObject
-- Desc:
-- Params:
-- return:


-- GuiControl

-- GFXInit
getAdapters
-- Desc:
-- Params:
-- return:


-- GuiCanvas
setVideoMode
-- Desc:
-- Params:
-- return:

getVideoMode
-- Desc:
-- Params:
-- return:

getAllVideoModes
-- Desc:
-- Params:
-- return:


-- TimeOfDay
-- LevelInfo

-- Prefab
load
-- Desc:
-- Params:
-- return:

unload
-- Desc:
-- Params:
-- return:

isLoaded
-- Desc:
-- Params:
-- return:

Prefab_getPrefabByChild
-- Desc:
-- Params:
-- return:


-- ScatterSky
setAzimuth
-- Desc:
-- Params:
-- return:

getAzimuth
-- Desc:
-- Params:
-- return:

-- CloudLayer
-- SpawnSphere
-- TSStatic
-- CameraBookmark
-- Forest
-- GroundCover
-- ForestWindEmitter
-- WaterObject
-- TerrainBlock
-- WaterBlock
-- Precipitation
-- DecalRoad
getNodeCount
-- Desc:
-- Params:
-- return:

getNodePosition
-- Desc:
-- Params:
-- return:

getNodeWidth
-- Desc:
-- Params:
-- return:

-- LightBase
-- PointLight
-- SpotLight
-- SFXEmitter
-- BeamNGTrigger
debug
-- Desc:
-- Params:
-- return:

color
-- Desc:
-- Params:
-- return:

force
-- Desc:
-- Params:
-- return:

-- BeamNGWaypoint
debugDrawAll
-- Desc:
-- Params:
-- return:


-- DebugDrawer
drawBox
-- Desc:
-- Params:
-- return:

drawSquarePrism
-- Desc:
-- Params:
-- return:

drawLine
-- Desc:
-- Params:
-- return:

drawTri
-- Desc:
-- Params:
-- return:

drawText
-- Desc:
-- Params:
-- return:

drawCylinder
-- Desc:
-- Params:
-- return:

drawSphere
-- Desc:
-- Params:
-- return:

setLastTTL
-- Desc:
-- Params:
-- return:

setLastZTest
-- Desc:
-- Params:
-- return:

-- BeamNGVehicle
getActionMap
-- Desc:
-- Params:
-- return:

getPath
-- Desc:
-- Params:
-- return:

getJBeamFilename
-- Desc:
-- Params:
-- return:

queueLuaCommand
-- Desc:
-- Params:
-- return:

playRPMLeds
-- Desc:
-- Params:
-- return:

getFFBID
-- Desc:
-- Params:
-- return:

sendForceFeedback
-- Desc:
-- Params:
-- return:

createUITexture
-- Desc:
-- Params:
-- return:

destroyUITexture
-- Desc:
-- Params:
-- return:

queueJSUITexture
-- Desc:
-- Params:
-- return:

isUITexture
-- Desc:
-- Params:
-- return:

getPhysicsID
-- Desc:
-- Params:
-- return:

playerUsable
-- Desc:
-- Params:
-- return:

resetCam
-- Desc:
-- Params:
-- return:

setCamModeByType
-- Desc:
-- Params:
-- return:

getCamRotation
-- Desc:
-- Params:
-- return:

setCamRotation
-- Desc:
-- Params:
-- return:

setCamFOV
-- Desc:
-- Params:
-- return:

getCamFOV
-- Desc:
-- Params:
-- return:

camGetMinDist
-- Desc:
-- Params:
-- return:

getCamDist
-- Desc:
-- Params:
-- return:

setCamDist
-- Desc:
-- Params:
-- return:

-- VirtualInputManager
resetDevices
registerDevice
emitEvent

-- Steam
triggerScreenshot
-- Desc:
-- Params:
-- return:

language
-- Desc:
-- Params:
-- return:

branch
-- Desc:
-- Params:
-- return:

playerName
-- Desc:
-- Params:
-- return:

accountID
-- Desc:
-- Params:
-- return:

authTicketValidated
-- Desc:
-- Params:
-- return:

isWorking
-- Desc:
-- Params:
-- return:

useSteam
-- Desc:
-- Params:
-- return:

accountLoggedIn
-- Desc:
-- Params:
-- return:

authTicket
-- Desc:
-- Params:
-- return:

setStat
-- Desc:
-- Params:
-- return:

-- SimpleSettings
fpslimiter

-- Sim
spawnObject
-- Desc:
-- Params:
-- return:

-- Engine.Audio
getInfo
-- Desc:
-- Params:
-- return:


-- Engine.Platform
getRealMilliseconds
-- Desc:
-- Params:
-- return:

getMemoryInfo
-- Desc:
-- Params:
-- return:

getCPUInfo
-- Desc:
-- Params:
-- return:

getGPUInfo
-- Desc:
-- Params:
-- return:

getOSInfo
-- Desc:
-- Params:
-- return:

getPowerInfo
-- Desc:
-- Params:
-- return:

exploreFolder
-- Desc:
-- Params:
-- return:

openFile
-- Desc:
-- Params:
-- return:

repaintCanvas
-- Desc:
-- Params:
-- return:

runBananaBench
-- Desc:
-- Params:
-- return:

startCommandListener
-- Desc:
-- Params:
-- return:

getStartingArgs
-- Desc:
-- Params:
-- return:

-- TorqueScript
eval
-- Desc:
-- Params:
-- return:

exec
-- Desc:
-- Params:
-- return:

-- GBitmap
init
-- Desc:
-- Params:
-- return:

getColor
-- Desc:
-- Params:
-- return:

setColor
-- Desc:
-- Params:
-- return:

fillColor
-- Desc:
-- Params:
-- return:

getWidth
-- Desc:
-- Params:
-- return:

getHeight
-- Desc:
-- Params:
-- return:

getBytesPerPixel
-- Desc:
-- Params:
-- return:

loadFile
-- Desc:
-- Params:
-- return:

saveFile
-- Desc:
-- Params:
-- return:

getPtr
-- Desc:
-- Params:
-- return:

-- global functions
getPerformanceMetrics
-- Desc:
-- Params:
-- return:

openWebBrowser
-- Desc:
-- Params:
-- return:

setClipboard
-- Desc:
-- Params:
-- return:

createScreenshot
-- Desc:
-- Params:
-- return:

getVirtualInputManager
-- Desc:
-- Params:
-- return:

showCefDevConsole
-- Desc:
-- Params:
-- return:

compileCollada
-- Desc:
-- Params:
-- return:

shutdown
-- Desc:
-- Params:
-- return:

forceShutdown
-- Desc:
-- Params:
-- return:

alertOK
-- Desc:
-- Params:
-- return:

setCEFFocus
-- Desc:
-- Params:
-- return:

getCEFFocusMouse
-- Desc:
-- Params:
-- return:

getCEFFocusMouseLastTimeMs
-- Desc:
-- Params:
-- return:

getMovedMouseLastTimeMs
-- Desc:
-- Params:
-- return:

getCEFFocusKeyboard
-- Desc:
-- Params:
-- return:

dot
-- Desc:
-- Params:
-- return:

getTSVar
-- Desc:
-- Params:
-- return:

setTSVar
-- Desc:
-- Params:
-- return:

getCameraPosition
-- Desc:
-- Params:
-- return:

-- global vars
Lua
be
FS
debugDrawer
cachepath
beamng_versionb
beamng_versiond
beamng_version
beamng_windowtitle
beamng_buildinfo
beamng_arch
beamng_buildnumber
beamng_appname

COMMAND_CONTEXT_TS
COMMAND_CONTEXT_UIJS
COMMAND_CONTEXT_VLUA
COMMAND_CONTEXT_ELUA
COMMAND_CONTEXT_TLUA
COMMAND_CONTEXT_SLUA
COMMAND_CONTEXT_BVLUA
UI_TEXTURE_USAGE_ONCE
UI_TEXTURE_USAGE_AUTOMATIC
UI_TEXTURE_USAGE_MANUAL

-- callbacks
luaPreRender
update
onFileChanged
vehicleSwitched
networkDataReady
init

Global functions

Global tables and classes

Global userdata objects

  • BeamEngine
  • FS
  • Lua
  • dir
  • gameEngine
  • kARGB_ClipLayer_SaveFlag
  • kARGB_NoClipLayer_SaveFlag
  • kBold
  • kBoldItalic
  • kCCW_Direction
  • kCW_Direction
  • kCenter_Align
  • kClipToLayer_SaveFlag
  • kClip_SaveFlag
  • kDifference_Op
  • kFill_Style
  • kFullColorLayer_SaveFlag
  • kHasAlphaLayer_SaveFlag
  • kIntersect_Op
  • kItalic
  • kLeft_Align
  • kMatrixClip_SaveFlag
  • kMatrix_SaveFlag
  • kNormal
  • kReplace_Op
  • kReverseDifference_Op
  • kRight_Align
  • kStrokeAndFill_Style
  • kStroke_Style
  • kUnion_Op
  • kUnknown_Direction
  • kXOR_Op
  • BeamObject obj
  • terrainBlock