utils Reference
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
jsonDecodeusesjsonDebug.lua(with duplicate key warnings) in non-shipping builds, andjson.luain shipping buildsjsonWriteFilesupports atomic writes (write to temp file, then rename) to prevent corruptiondeepcopyhandles circular references via a lookup table- The
serializefunction produces valid Lua source that can beloadstring'd tableMergeRecursiveArrayhas special handling: arrays are concatenated (appended), not replaced or merged element-by-elementconcatWorkBufferandstringFormatWorkBufferreuse internalstring.bufferobjects to avoid GC pressuredumpshandles: nil, boolean, number, string, table (with circular reference detection), vec3, quat, cdata
timeEvents Reference
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.