Lua Standard Libraries
Standard Lua libraries available in the MudForge plugin environment. These are JavaScript implementations that mirror Lua’s standard library behavior.
table
Table manipulation functions for working with Lua tables (arrays and dictionaries).
table.concat
Concatenate array elements into a string.
table.concat(tbl, sep?, i?, j?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| tbl | table | Yes | - | The array to concatenate |
| sep | string | No | "" | Separator between elements |
| i | number | No | 1 | Start index |
| j | number | No | #tbl | End index |
Returns: string - Concatenated string.
Example:
local arr = {"a", "b", "c"}
print(table.concat(arr)) -- "abc"
print(table.concat(arr, ", ")) -- "a, b, c"
print(table.concat(arr, "-", 1, 2)) -- "a-b"table.insert
Insert an element into an array.
table.insert(tbl, pos?, value)| Parameter | Type | Required | Description |
|---|---|---|---|
| tbl | table | Yes | The array to modify |
| pos | number | No | Position to insert (if omitted, appends to end) |
| value | any | Yes | Value to insert |
Example:
local arr = {1, 2, 3}
table.insert(arr, 4) -- {1, 2, 3, 4}
table.insert(arr, 2, 1.5) -- {1, 1.5, 2, 3, 4}table.remove
Remove and return an element from an array.
table.remove(tbl, pos?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| tbl | table | Yes | - | The array to modify |
| pos | number | No | #tbl | Position to remove (defaults to last element) |
Returns: any - The removed element.
Example:
local arr = {1, 2, 3, 4}
local last = table.remove(arr) -- returns 4, arr = {1, 2, 3}
local second = table.remove(arr, 2) -- returns 2, arr = {1, 3}table.sort
Sort an array in-place.
table.sort(tbl, comp?)| Parameter | Type | Required | Description |
|---|---|---|---|
| tbl | table | Yes | The array to sort |
| comp | function | No | Comparison function(a, b) returning true if a < b |
Example:
local arr = {3, 1, 4, 1, 5}
table.sort(arr) -- {1, 1, 3, 4, 5}
-- Custom sort (descending)
table.sort(arr, function(a, b) return a > b end) -- {5, 4, 3, 1, 1}
-- Sort by property
local players = {{name="Bob", score=10}, {name="Alice", score=20}}
table.sort(players, function(a, b) return a.score > b.score end)table.maxn
Find the largest positive numeric index in a table.
table.maxn(tbl)| Parameter | Type | Required | Description |
|---|---|---|---|
| tbl | table | Yes | The table to check |
Returns: number - The largest numeric index, or 0 if none.
Example:
local t = {}
t[1] = "a"
t[100] = "b"
print(table.maxn(t)) -- 100table.unpack
Unpack array elements as multiple return values.
table.unpack(tbl, i?, j?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| tbl | table | Yes | - | The array to unpack |
| i | number | No | 1 | Start index |
| j | number | No | #tbl | End index |
Returns: Multiple values from the array.
Example:
local arr = {10, 20, 30}
local a, b, c = table.unpack(arr) -- a=10, b=20, c=30
print(a, b, c)
-- Partial unpack
local x, y = table.unpack(arr, 2, 3) -- x=20, y=30math
Mathematical functions and constants.
Constants
| Constant | Value | Description |
|---|---|---|
math.pi | 3.14159… | Pi (π) |
math.huge | Infinity | Positive infinity |
Basic Functions
math.abs(x) -- Absolute value
math.floor(x) -- Round down
math.ceil(x) -- Round up
math.min(...) -- Minimum of arguments
math.max(...) -- Maximum of arguments
math.sqrt(x) -- Square root
math.pow(x, y) -- x raised to power y
math.fmod(x, y) -- Remainder of x/yExample:
print(math.abs(-5)) -- 5
print(math.floor(3.7)) -- 3
print(math.ceil(3.2)) -- 4
print(math.min(1, 5, 3)) -- 1
print(math.max(1, 5, 3)) -- 5
print(math.sqrt(16)) -- 4
print(math.pow(2, 8)) -- 256Trigonometric Functions
math.sin(x) -- Sine (x in radians)
math.cos(x) -- Cosine
math.tan(x) -- Tangent
math.asin(x) -- Arc sine
math.acos(x) -- Arc cosine
math.atan(x) -- Arc tangent
math.atan2(y, x) -- Arc tangent of y/x
math.sinh(x) -- Hyperbolic sine
math.cosh(x) -- Hyperbolic cosine
math.tanh(x) -- Hyperbolic tangentAngle Conversion
math.deg(radians) -- Convert radians to degrees
math.rad(degrees) -- Convert degrees to radiansExample:
print(math.deg(math.pi)) -- 180
print(math.rad(180)) -- 3.14159...Logarithmic Functions
math.log(x) -- Natural logarithm
math.log10(x) -- Base-10 logarithm
math.exp(x) -- e^xRandom Numbers
math.random() -- Random float in [0, 1)
math.random(m) -- Random integer in [1, m]
math.random(m, n) -- Random integer in [m, n]
math.randomseed(x) -- Seed the random generator (no effect in browser)Example:
print(math.random()) -- 0.7234... (random float)
print(math.random(6)) -- 1-6 (dice roll)
print(math.random(10, 20)) -- 10-20 (random in range)Special Functions
math.frexp(x) -- Returns mantissa and exponent: m, e where x = m * 2^e
math.ldexp(m, e) -- Returns m * 2^e
math.modf(x) -- Returns integer and fractional partsstring
String manipulation functions.
string.len
Get string length.
string.len(s)
-- or
#sExample:
print(string.len("hello")) -- 5
print(#"hello") -- 5string.sub
Extract a substring.
string.sub(s, i, j?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| s | string | Yes | - | The string |
| i | number | Yes | - | Start index (1-based, negative counts from end) |
| j | number | No | -1 | End index |
Example:
local s = "Hello, World!"
print(string.sub(s, 1, 5)) -- "Hello"
print(string.sub(s, 8)) -- "World!"
print(string.sub(s, -6)) -- "World!"
print(string.sub(s, -6, -2)) -- "World"string.upper / string.lower
Convert case.
string.upper(s)
string.lower(s)Example:
print(string.upper("hello")) -- "HELLO"
print(string.lower("HELLO")) -- "hello"string.rep
Repeat a string.
string.rep(s, n, sep?)| Parameter | Type | Required | Description |
|---|---|---|---|
| s | string | Yes | String to repeat |
| n | number | Yes | Number of repetitions |
| sep | string | No | Separator between repetitions |
Example:
print(string.rep("ab", 3)) -- "ababab"
print(string.rep("x", 5, "-")) -- "x-x-x-x-x"string.reverse
Reverse a string.
string.reverse(s)Example:
print(string.reverse("hello")) -- "olleh"string.byte
Get character code(s).
string.byte(s, i?, j?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| s | string | Yes | - | The string |
| i | number | No | 1 | Start index |
| j | number | No | i | End index |
Returns: One or more numeric character codes.
Example:
print(string.byte("ABC")) -- 65
print(string.byte("ABC", 2)) -- 66
print(string.byte("ABC", 1, 3)) -- 65, 66, 67string.char
Create string from character codes.
string.char(...)Example:
print(string.char(65, 66, 67)) -- "ABC"
print(string.char(72, 105)) -- "Hi"string.find
Find pattern in string.
string.find(s, pattern, init?, plain?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| s | string | Yes | - | The string to search |
| pattern | string | Yes | - | Pattern to find |
| init | number | No | 1 | Start position |
| plain | boolean | No | false | If true, pattern is plain text (no regex) |
Returns: start, end indices, or nil if not found.
Example:
local s = "Hello, World!"
local start, finish = string.find(s, "World")
print(start, finish) -- 8, 12
-- Plain text search
local i, j = string.find("a.b.c", ".", 1, true)
print(i, j) -- 2, 2string.match
Extract pattern match.
string.match(s, pattern, init?)Returns: Captured groups, or the whole match if no captures.
Example:
local s = "name: John, age: 30"
print(string.match(s, "name: (%w+)")) -- "John"
print(string.match(s, "age: (%d+)")) -- "30"string.gsub
Global substitution.
string.gsub(s, pattern, repl, n?)| Parameter | Type | Required | Description |
|---|---|---|---|
| s | string | Yes | The string |
| pattern | string | Yes | Pattern to replace |
| repl | string/function/table | Yes | Replacement |
| n | number | No | Max replacements |
Returns: new_string, count (modified string and number of replacements).
Example:
local s = "hello world"
print(string.gsub(s, "l", "L")) -- "heLLo worLd", 3
print(string.gsub(s, "l", "L", 2)) -- "heLLo world", 2
-- Function replacement
local result = string.gsub("abc", ".", function(c)
return string.upper(c)
end)
print(result) -- "ABC"string.format
Format a string (like C’s sprintf).
string.format(formatstring, ...)Format Specifiers:
%s- string%d- integer%f- float%x- hexadecimal%%- literal %
Example:
print(string.format("Hello, %s!", "World")) -- "Hello, World!"
print(string.format("HP: %d/%d", 50, 100)) -- "HP: 50/100"
print(string.format("Pi: %.2f", 3.14159)) -- "Pi: 3.14"
print(string.format("Hex: %x", 255)) -- "Hex: ff"os
Operating system functions (web-safe implementation).
os.clock
Get elapsed CPU time in seconds.
os.clock()Returns: number - Elapsed time since page load (using performance.now()).
Example:
local start = os.clock()
-- ... do work ...
local elapsed = os.clock() - start
print("Took " .. elapsed .. " seconds")os.time
Get current Unix timestamp.
os.time(table?)| Parameter | Type | Required | Description |
|---|---|---|---|
| table | table | No | Date table with year, month, day, etc. |
Returns: number - Unix timestamp in seconds.
Example:
print(os.time()) -- Current timestamp
-- Create timestamp from date
local t = os.time({year=2024, month=6, day=15})os.date
Format a date/time.
os.date(format?, time?)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| format | string | No | ”%c” | Format string or “*t” for table |
| time | number | No | now | Unix timestamp |
Returns: Formatted string or table (if format is “*t”).
Format Specifiers:
%Y- 4-digit year%m- month (01-12)%d- day (01-31)%H- hour (00-23)%M- minute (00-59)%S- second (00-59)%a- abbreviated weekday%A- full weekday%b- abbreviated month%B- full month
Example:
print(os.date()) -- "Sat Jun 15 14:30:45 2024"
print(os.date("%Y-%m-%d")) -- "2024-06-15"
print(os.date("%H:%M:%S")) -- "14:30:45"
-- Get date table
local t = os.date("*t")
print(t.year, t.month, t.day) -- 2024, 6, 15
print(t.hour, t.min, t.sec) -- 14, 30, 45
print(t.wday) -- 7 (Saturday, 1=Sunday)os.difftime
Calculate time difference.
os.difftime(t2, t1)Returns: number - Difference in seconds.
Example:
local start = os.time()
-- ... later ...
local elapsed = os.difftime(os.time(), start)
print("Elapsed: " .. elapsed .. " seconds")Iterators
Functions for iterating over tables.
pairs
Iterate over all key-value pairs in a table.
for key, value in pairs(tbl) do
-- process
endExample:
local player = {name = "Hero", level = 50, class = "Warrior"}
for k, v in pairs(player) do
print(k .. " = " .. tostring(v))
end
-- Output (order may vary):
-- name = Hero
-- level = 50
-- class = Warrioripairs
Iterate over array elements in order.
for index, value in ipairs(arr) do
-- process
endExample:
local items = {"sword", "shield", "potion"}
for i, item in ipairs(items) do
print(i .. ": " .. item)
end
-- Output:
-- 1: sword
-- 2: shield
-- 3: potionNote:
ipairsstops at the firstnilvalue. Usepairsfor sparse arrays.
Notes on JavaScript Implementation
Differences from Standard Lua
-
Table Indexing: Lua tables are 1-indexed. The JavaScript implementation maintains this behavior for compatibility.
-
Random Numbers:
math.randomseed()has no effect since JavaScript’sMath.random()cannot be seeded. -
Pattern Matching: String patterns use JavaScript regular expressions internally. Most common Lua patterns work, but complex Lua-specific patterns may behave differently.
-
File I/O: The
iolibrary is not available in the browser environment. -
os.execute: Not available for security reasons.
Best Practices
-- Use ipairs for arrays (faster, ordered)
local arr = {1, 2, 3, 4, 5}
for i, v in ipairs(arr) do
print(v)
end
-- Use pairs for dictionaries
local dict = {a = 1, b = 2, c = 3}
for k, v in pairs(dict) do
print(k, v)
end
-- Check for nil before accessing properties
local myTable = { key = "hello" } -- Define the table first
local value = myTable.key
if value then
print(value)
end
-- Safe access pattern for potentially nil tables
local data = someTable and someTable.key or "default"
-- Use table.concat for string building (more efficient than ..)
local parts = {"Hello", " ", "World"}
local result = table.concat(parts) -- "Hello World"