RLS Studios
ProjectsPatreonCommunityDocsAbout
Join Patreon
BeamNG Modding Docs

Guides

Reference

Debug DrawingGPU Mesh StructsImGui FFIMath Structs (FFI)FFI C DefinitionsPID ControllersCSV LibraryDelay LineDequeDevelopment UtilitiesEvent ReferenceExtension SystemSignal FiltersGraph PathfindingUI BridgeInput Filter Constants2D Bilinear InterpolationIntrospectionJBeam Pretty PrinterJSON AST ParserSJSON ParserJSON Debug ParserJSON Pretty PrinterK-D Tree (2D Boxes)K-D Tree (3D)K-D Tree (3D)Lua SerializerC++/Lua BindingLua CoreLua ProfilerMath LibraryParticlesQuadtreeSettingsTCP ServerTimer SchedulerUtility Library

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 Referencecommon

Utility Library

Module defined in `lua/common/utils.lua`. Massive utility library providing color functions, JSON encoding/decoding, table manipulation, string utilities, file I/O, serialization, debugging tools, and

Module defined in lua/common/utils.lua. Massive utility library providing color functions, JSON encoding/decoding, table manipulation, string utilities, file I/O, serialization, debugging tools, and more. Required by virtually everything.


Exports

All exports are global functions (no module table). Also requires filters, inputFilters, and lpack.

Color Functions

RGBtoHSV(r, g, b) → h, s, v

HSVtoRGB(h, s, v) → r, g, b

rainbowColor(numOfSteps, step, format) → table - {r, g, b, a} (format: 255 or 1)

color(r, g, b, a) → number - Packs RGBA (0-255) into a single 32-bit integer

colorGetRGBA(col) → r, g, b, a - Unpacks a packed color

colorHex(rgbHex, a) → number - Creates packed color from hex RGB + alpha

tableToColor(v) → number - Converts {r, g, b, a} table to packed color

parseColor(v) → number - Parses color from table or hex string

ironbowColor(x, a) / jetColor(x, a) / greyColor(x, a) → number - Colormap functions (x in 0-1)

Debug / Dump Functions

dumps(...) → string - Serializes values to readable string

dump(...) - Prints serialized values to console

dumpsz(o, depth) → string - Depth-limited dumps

dumpz(o, depth) - Depth-limited dump to console

dumpToFile(filename, ...) - Dumps to file

dumpNotNil(x) - Only dumps if not nil

String Functions

lpad(s, l, c) / rpad(s, l, c) → string - Left/right pad

trim(s) → string - Trim whitespace

split(str, delim, nMax) → table - Split string by delimiter

stringHash(text) → number - DJB2 hash

string.startswith(s, start) / string.endswith(s, end) → boolean

string.stripchars(s, chrs) / string.rstripchars(s, chrs) → string

string.split(str, delimregex) → table

string.sentenceCase(str) → string

bytes_to_string(bytes) → string - Human-readable byte size

hex_dump(str) - Prints hex dump of string

formatTimeStringNow(res) → string - Current time with optional resolution

JSON Functions

jsonEncode(v) → string - Encodes Lua value to compact JSON

jsonEncodeWorkBuffer(v) → buffer - Encodes to work buffer (no copy)

jsonEncodePretty(v, lvl, numberPrecision) → string - Pretty-printed JSON

jsonDecode(content, context) → table - Decodes JSON string (uses json.lua or jsonDebug.lua)

jsonWriteFile(filename, obj, pretty, numberPrecision, atomicWrite) → boolean

jsonReadFile(filename) → table|nil

readDictJSONTable(filename) → table - Reads JSON file that's a dict of dicts

Table Functions

tableIsEmpty(tbl) → boolean

tableIsDict(tbl) → boolean - Heuristic: true if first key (via next()) is not 1. Fast but not exhaustive - use tableIsArraySlow for thorough checks

tableKeys(tbl, target) → table - Array of keys

tableKeysSorted(tbl, target) → table - Sorted array of keys (handles mixed types)

tableValuesAsLookupDict(tbl, target) → table - Values become keys with true

tableMerge(dst, src) - Shallow merge src into dst

tableMergeRecursive(t1, t2) - Deep merge

tableMergeRecursiveArray(t1, t2) - Deep merge preserving arrays

tableSize(tbl) → number - Count of all entries

tableSizeC(tbl) → number - Cached table size

tableEndC(tbl) → number - Cached last array index

tableInsertC(tbl, data) - Insert tracking count

tableReadOnly(tbl) → table - Returns a read-only proxy

tableFindKey(t, element) → key|nil

tableContains(t, element) → boolean

tableContainsCaseInsensitive(t, element) → boolean

tableRoundRobinKey(tbl, lastKey) → key

tableDepth(tbl, lookup) → number - Max nesting depth

arrayConcat(dst, src) - Append src array to dst

arrayFindValueIndex(t, val) → number|nil

arrayShuffle(array) - In-place Fisher-Yates shuffle

arrayReverse(array) - In-place reverse

shallowcopy(orig) → table

deepcopy(object) → any

checkTableDataTypes(data, expectedTypes) → boolean, string|nil - Validate table field types

flattenTable(tbl) / unflattenTable(tbl) - Flatten/unflatten nested tables with path keys

setEqual(set1, set2) → boolean

setUnion(dst, src) → table

setDifference(dst, src) → table

File I/O

readFile(filename) → string|nil - Reads entire file

readFiles(filenames, maxBatchSize) → table - Batch read files

writeFile(filename, data) → boolean

Serialization

serialize(v) → string - Serialize Lua value to evaluable string

serializeWorkBuffer(v) → buffer

deserialize(s) → any - Deserialize via loadstring

serializePackages(reason) → table - Serialize global module state

deserializePackages(data, filter) - Restore global modules from serialized data

Iteration

sortedPairs(t, ctx, f) → function - Iterator over sorted keys

shuffledPairs(t, ctx) → function - Iterator in random order

Debug Utilities

detectGlobalWrites() - Sets up global write detection metatable

gcprobe(printZero, omitPrint) → table - Measures GC impact of code between calls

timeprobeStart() / timeprobe(omitPrint) → number - High-precision timing

jitprobe() - Dumps JIT trace info

simpleDebugText3d(text, pos, radius, sphereColor, dir) - Draws debug text in 3D

graphs(v, len) → string - Simple ASCII bar graph

Level Functions

getCurrentLevelIdentifier(raw) → string|nil

getAllLevelIdentifiers() → table

INI File Functions

loadIni(filename) → table - Parses INI file to table

saveIni(filename, d) - Writes table as INI file

Misc Functions

ui_message(msg, ttl, category, icon) - Sends UI toast message

concatWorkBuffer(...) → string - Efficient string concatenation

stringFormatWorkBuffer(...) → string - Efficient string.format

addLevelLog(object, logLevel, origin, uniqueErrorCode, message) / getLevelLogs() / clearLevelLogs()

clearLevelLogs()

Clears accumulated level log messages.

dirname(filename)

Returns the directory portion of a file path.

getCurrentPath()

Returns the current working path.

getLevelLogs()

Returns accumulated level log messages.

getPathLevelInfo(levelName)

Extracts level info metadata from a path.

getPathLevelMain(levelName)

Returns the main level path from a given path.

greyColor(x, a)

Returns a grey color value (r=g=b=v).

is_file(filename)

Returns true if the path points to an existing file.

jetColor(x, a)

Returns a jet colormap color for value v (0-1 range).

jsonEncodePrefix(prefix, v, postfix)

JSON-encodes an object with a string prefix.

levelFromPath(filepath)

Extracts the level name from a file path.

rpad(s, l, c)

Right-pads a string to the given length with the specified character.

splitWithoutExt(filepath, compositeExtension)

Splits a path and removes the file extension.

stripcharsFrontBack(str, chrs)

Strips specified characters from both ends of a string.

tableIsArraySlow(tbl)

Returns true if a table is a pure array (sequential integer keys). Slower but more thorough than tableIsArray.

timeprobe(omitPrint)

Creates a named time probe for performance measurement.

unflattenTable(tbl)

Reconstructs a nested table from a flattened key-path representation.

Internal Notes

  • jsonDecode uses jsonDebug.lua (with duplicate key warnings) in non-shipping builds, and json.lua in shipping builds
  • jsonWriteFile supports atomic writes (write to temp file, then rename) to prevent corruption
  • deepcopy handles circular references via a lookup table
  • The serialize function produces valid Lua source that can be loadstring'd
  • tableMergeRecursiveArray has special handling: arrays are concatenated (appended), not replaced or merged element-by-element
  • concatWorkBuffer and stringFormatWorkBuffer reuse internal string.buffer objects to avoid GC pressure
  • dumps handles: nil, boolean, number, string, table (with circular reference detection), vec3, quat, cdata

See Also

  • cdefDebugDraw Reference - Related reference
  • cdefGpuMesh Reference - Related reference
  • cdefImgui Reference - Related reference
  • Common Libraries Overview - Guide

Timer Scheduler

Module defined in `lua/common/timeEvents.lua`. A lightweight timer/scheduler that lets you schedule function callbacks to fire after a specified delay. Similar to the global `schedule()` function.

extensions/ - BeamNG Extension Modules

Extension modules that integrate with BeamNG's hook system. Organized by subsystem.

On this page

ExportsColor FunctionsRGBtoHSV(r, g, b) → h, s, vHSVtoRGB(h, s, v) → r, g, brainbowColor(numOfSteps, step, format) → table - {r, g, b, a} (format: 255 or 1)color(r, g, b, a) → number - Packs RGBA (0-255) into a single 32-bit integercolorGetRGBA(col) → r, g, b, a - Unpacks a packed colorcolorHex(rgbHex, a) → number - Creates packed color from hex RGB + alphatableToColor(v) → number - Converts {r, g, b, a} table to packed colorparseColor(v) → number - Parses color from table or hex stringironbowColor(x, a) / jetColor(x, a) / greyColor(x, a) → number - Colormap functions (x in 0-1)Debug / Dump Functionsdumps(...) → string - Serializes values to readable stringdump(...) - Prints serialized values to consoledumpsz(o, depth) → string - Depth-limited dumpsdumpz(o, depth) - Depth-limited dump to consoledumpToFile(filename, ...) - Dumps to filedumpNotNil(x) - Only dumps if not nilString Functionslpad(s, l, c) / rpad(s, l, c) → string - Left/right padtrim(s) → string - Trim whitespacesplit(str, delim, nMax) → table - Split string by delimiterstringHash(text) → number - DJB2 hashstring.startswith(s, start) / string.endswith(s, end) → booleanstring.stripchars(s, chrs) / string.rstripchars(s, chrs) → stringstring.split(str, delimregex) → tablestring.sentenceCase(str) → stringbytes_to_string(bytes) → string - Human-readable byte sizehex_dump(str) - Prints hex dump of stringformatTimeStringNow(res) → string - Current time with optional resolutionJSON FunctionsjsonEncode(v) → string - Encodes Lua value to compact JSONjsonEncodeWorkBuffer(v) → buffer - Encodes to work buffer (no copy)jsonEncodePretty(v, lvl, numberPrecision) → string - Pretty-printed JSONjsonDecode(content, context) → table - Decodes JSON string (uses json.lua or jsonDebug.lua)jsonWriteFile(filename, obj, pretty, numberPrecision, atomicWrite) → booleanjsonReadFile(filename) → table|nilreadDictJSONTable(filename) → table - Reads JSON file that's a dict of dictsTable FunctionstableIsEmpty(tbl) → booleantableIsDict(tbl) → boolean - Heuristic: true if first key (via next()) is not 1. Fast but not exhaustive - use tableIsArraySlow for thorough checkstableKeys(tbl, target) → table - Array of keystableKeysSorted(tbl, target) → table - Sorted array of keys (handles mixed types)tableValuesAsLookupDict(tbl, target) → table - Values become keys with truetableMerge(dst, src) - Shallow merge src into dsttableMergeRecursive(t1, t2) - Deep mergetableMergeRecursiveArray(t1, t2) - Deep merge preserving arraystableSize(tbl) → number - Count of all entriestableSizeC(tbl) → number - Cached table sizetableEndC(tbl) → number - Cached last array indextableInsertC(tbl, data) - Insert tracking counttableReadOnly(tbl) → table - Returns a read-only proxytableFindKey(t, element) → key|niltableContains(t, element) → booleantableContainsCaseInsensitive(t, element) → booleantableRoundRobinKey(tbl, lastKey) → keytableDepth(tbl, lookup) → number - Max nesting deptharrayConcat(dst, src) - Append src array to dstarrayFindValueIndex(t, val) → number|nilarrayShuffle(array) - In-place Fisher-Yates shufflearrayReverse(array) - In-place reverseshallowcopy(orig) → tabledeepcopy(object) → anycheckTableDataTypes(data, expectedTypes) → boolean, string|nil - Validate table field typesflattenTable(tbl) / unflattenTable(tbl) - Flatten/unflatten nested tables with path keyssetEqual(set1, set2) → booleansetUnion(dst, src) → tablesetDifference(dst, src) → tableFile I/OreadFile(filename) → string|nil - Reads entire filereadFiles(filenames, maxBatchSize) → table - Batch read fileswriteFile(filename, data) → booleanSerializationserialize(v) → string - Serialize Lua value to evaluable stringserializeWorkBuffer(v) → bufferdeserialize(s) → any - Deserialize via loadstringserializePackages(reason) → table - Serialize global module statedeserializePackages(data, filter) - Restore global modules from serialized dataIterationsortedPairs(t, ctx, f) → function - Iterator over sorted keysshuffledPairs(t, ctx) → function - Iterator in random orderDebug UtilitiesdetectGlobalWrites() - Sets up global write detection metatablegcprobe(printZero, omitPrint) → table - Measures GC impact of code between callstimeprobeStart() / timeprobe(omitPrint) → number - High-precision timingjitprobe() - Dumps JIT trace infosimpleDebugText3d(text, pos, radius, sphereColor, dir) - Draws debug text in 3Dgraphs(v, len) → string - Simple ASCII bar graphLevel FunctionsgetCurrentLevelIdentifier(raw) → string|nilgetAllLevelIdentifiers() → tableINI File FunctionsloadIni(filename) → table - Parses INI file to tablesaveIni(filename, d) - Writes table as INI fileMisc Functionsui_message(msg, ttl, category, icon) - Sends UI toast messageconcatWorkBuffer(...) → string - Efficient string concatenationstringFormatWorkBuffer(...) → string - Efficient string.formataddLevelLog(object, logLevel, origin, uniqueErrorCode, message) / getLevelLogs() / clearLevelLogs()clearLevelLogs()dirname(filename)getCurrentPath()getLevelLogs()getPathLevelInfo(levelName)getPathLevelMain(levelName)greyColor(x, a)is_file(filename)jetColor(x, a)jsonEncodePrefix(prefix, v, postfix)levelFromPath(filepath)rpad(s, l, c)splitWithoutExt(filepath, compositeExtension)stripcharsFrontBack(str, chrs)tableIsArraySlow(tbl)timeprobe(omitPrint)unflattenTable(tbl)Internal NotesSee Also