Standard Lua Libraries
Standard Lua Libraries
Section titled “Standard Lua Libraries”Core Lua libraries automatically available in all Wippy processes. No require() needed.
Global Functions
Section titled “Global Functions”Type and Conversion
Section titled “Type and Conversion”type(value) -- Returns: "nil", "number", "string", "boolean", "table", "function", "thread", "userdata"tonumber(s [,base]) -- Convert to number, optional base (2-36)tostring(value) -- Convert to string, calls __tostring metamethodAssertions and Errors
Section titled “Assertions and Errors”assert(v [,msg]) -- Raises error if v is false/nil, returns v otherwiseerror(msg [,level]) -- Raises error at specified stack level (default 1)pcall(fn, ...) -- Protected call, returns ok, result_or_errorxpcall(fn, errh) -- Protected call with error handler functionTable Iteration
Section titled “Table Iteration”pairs(t) -- Iterate all key-value pairsipairs(t) -- Iterate array portion (1, 2, 3, ...)next(t [,index]) -- Get next key-value pair after indexMetatables
Section titled “Metatables”getmetatable(obj) -- Get metatable (or __metatable field if protected)setmetatable(t, mt) -- Set metatable, returns tRaw Table Access
Section titled “Raw Table Access”Bypass metamethods for direct table access:
rawget(t, k) -- Get t[k] without __indexrawset(t, k, v) -- Set t[k]=v without __newindexrawequal(a, b) -- Compare without __eqUtilities
Section titled “Utilities”select(index, ...) -- Return args from index onwardsselect("#", ...) -- Return number of argsunpack(t [,i [,j]]) -- Return t[i] through t[j] as multiple valuesprint(...) -- Print values (uses structured logging in Wippy)Global Variables
Section titled “Global Variables”_G -- The global environment table_VERSION -- Lua version stringTable Manipulation
Section titled “Table Manipulation”Functions for modifying tables:
table.insert(t, [pos,] value) -- Insert value at pos (default: end)table.remove(t [,pos]) -- Remove and return element at pos (default: last)table.concat(t [,sep [,i [,j]]]) -- Concatenate array elements with separatortable.sort(t [,comp]) -- Sort in place, comp(a,b) returns true if a < btable.unpack(t [,i [,j]]) -- Unpack table elements as multiple valueslocal items = {"a", "b", "c"}
table.insert(items, "d") -- {"a", "b", "c", "d"}table.insert(items, 2, "x") -- {"a", "x", "b", "c", "d"}table.remove(items, 2) -- {"a", "b", "c", "d"}, returns "x"
local csv = table.concat(items, ",") -- "a,b,c,d"
table.sort(items, function(a, b) return a > b -- Descending orderend)String Operations
Section titled “String Operations”String manipulation functions. Also available as methods on string values:
Pattern Matching
Section titled “Pattern Matching”string.find(s, pattern [,init [,plain]]) -- Find pattern, returns start, end, capturesstring.match(s, pattern [,init]) -- Extract matching substringstring.gmatch(s, pattern) -- Iterator over all matchesstring.gsub(s, pattern, repl [,n]) -- Replace matches, returns string, countCase Conversion
Section titled “Case Conversion”string.upper(s) -- Convert to uppercasestring.lower(s) -- Convert to lowercaseSubstrings and Characters
Section titled “Substrings and Characters”string.sub(s, i [,j]) -- Substring from i to j (negative indexes from end)string.len(s) -- String length (or use #s)string.byte(s [,i [,j]]) -- Numeric codes of charactersstring.char(...) -- Create string from character codesstring.rep(s, n) -- Repeat string n timesstring.reverse(s) -- Reverse stringFormatting
Section titled “Formatting”string.format(fmt, ...) -- Printf-style formattingFormat specifiers: %d (integer), %f (float), %s (string), %q (quoted), %x (hex), %o (octal), %e (scientific), %% (literal %)
local s = "Hello, World!"
-- Pattern matchinglocal start, stop = string.find(s, "World") -- 8, 12local word = string.match(s, "%w+") -- "Hello"
-- Substitutionlocal new = string.gsub(s, "World", "Wippy") -- "Hello, Wippy!"
-- Method syntaxlocal upper = s:upper() -- "HELLO, WORLD!"local part = s:sub(1, 5) -- "Hello"Patterns
Section titled “Patterns”| Pattern | Matches |
|---|---|
. | Any character |
%a | Letters |
%d | Digits |
%w | Alphanumeric |
%s | Whitespace |
%p | Punctuation |
%c | Control characters |
%x | Hexadecimal digits |
%z | Zero (null) |
[set] | Character class |
[^set] | Negated class |
* | 0 or more (greedy) |
+ | 1 or more (greedy) |
- | 0 or more (lazy) |
? | 0 or 1 |
^ | Start of string |
$ | End of string |
%b() | Balanced pair |
(...) | Capture group |
Uppercase versions (%A, %D, etc.) match the complement.
Math Functions
Section titled “Math Functions”Mathematical functions and constants:
Constants {id=“math-constants”}
Section titled “Constants {id=“math-constants”}”math.pi -- 3.14159...math.huge -- Infinitymath.mininteger -- Minimum integermath.maxinteger -- Maximum integerBasic Operations
Section titled “Basic Operations”math.abs(x) -- Absolute valuemath.min(...) -- Minimum of argumentsmath.max(...) -- Maximum of argumentsmath.floor(x) -- Round downmath.ceil(x) -- Round upmath.modf(x) -- Integer and fractional partsmath.fmod(x, y) -- Floating-point remainderPowers and Roots
Section titled “Powers and Roots”math.sqrt(x) -- Square rootmath.pow(x, y) -- x^y (or use x^y operator)math.exp(x) -- e^xmath.log(x) -- Natural logmath.log10(x) -- Base-10 logTrigonometry
Section titled “Trigonometry”math.sin(x) math.cos(x) math.tan(x) -- Radiansmath.asin(x) math.acos(x) math.atan(x)math.atan2(y, x) -- Arc tangent of y/xmath.sinh(x) math.cosh(x) math.tanh(x) -- Hyperbolicmath.deg(r) -- Radians to degreesmath.rad(d) -- Degrees to radiansRandom Numbers
Section titled “Random Numbers”math.random() -- Random float [0,1)math.random(n) -- Random integer [1,n]math.random(m, n) -- Random integer [m,n]math.randomseed(x) -- Set random seedType Conversion
Section titled “Type Conversion”math.tointeger(x) -- Convert to integer or nilmath.type(x) -- "integer", "float", or nilmath.ult(m, n) -- Unsigned less-than comparisonCoroutines
Section titled “Coroutines”Coroutine creation and control. See Channels and Coroutines for channels and concurrent patterns:
coroutine.create(fn) -- Create coroutine from functioncoroutine.resume(co, ...) -- Start/continue coroutinecoroutine.yield(...) -- Suspend coroutine, return values to resumecoroutine.status(co) -- "running", "suspended", "normal", "dead"coroutine.running() -- Current coroutine (nil if main thread)coroutine.wrap(fn) -- Create coroutine as callable functionSpawning Concurrent Coroutines
Section titled “Spawning Concurrent Coroutines”Spawn a concurrent coroutine that runs independently (Wippy-specific):
coroutine.spawn(fn) -- Spawn function as concurrent coroutine-- Spawn background taskcoroutine.spawn(function() while true do check_health() time.sleep("30s") endend)
-- Continue main execution immediatelyprocess_request()Error Handling
Section titled “Error Handling”Structured error creation and classification. See Error Handling for full documentation:
Constants {id=“error-constants”}
Section titled “Constants {id=“error-constants”}”errors.UNKNOWN -- Unclassified errorerrors.INVALID -- Invalid argument or inputerrors.NOT_FOUND -- Resource not founderrors.ALREADY_EXISTS -- Resource already existserrors.PERMISSION_DENIED -- Permission deniederrors.TIMEOUT -- Operation timed outerrors.CANCELED -- Operation cancellederrors.UNAVAILABLE -- Service unavailableerrors.INTERNAL -- Internal errorerrors.CONFLICT -- Conflict (e.g., concurrent modification)errors.RATE_LIMITED -- Rate limit exceededFunctions {id=“error-functions”}
Section titled “Functions {id=“error-functions”}”-- Create error from stringlocal err = errors.new("something went wrong")
-- Create error with metadatalocal err = errors.new({ message = "User not found", kind = errors.NOT_FOUND, retryable = false, details = {user_id = 123}})
-- Wrap existing error with contextlocal wrapped = errors.wrap(err, "failed to load profile")
-- Check error kindif errors.is(err, errors.NOT_FOUND) then -- handle not foundend
-- Get call stack from errorlocal stack = errors.call_stack(err)Error Methods
Section titled “Error Methods”err:message() -- Get error message stringerr:kind() -- Get error kind (e.g., "NOT_FOUND")err:retryable() -- true, false, or nil (unknown)err:details() -- Get details table or nilerr:stack() -- Get stack trace as stringRestricted Features
Section titled “Restricted Features”The following standard Lua features are NOT available for security:
| Feature | Alternative |
|---|---|
load, loadstring, loadfile, dofile | Use Dynamic Evaluation module |
collectgarbage | Automatic GC |
rawlen | Use # operator |
io.* | Use File System module |
os.execute, os.exit, os.remove, os.rename, os.tmpname | Use Command Execution, Environment modules |
debug.* | Not available |
utf8.* | Not available |
package.loadlib | Native libraries not supported |
See Also
Section titled “See Also”- Channels and Coroutines - Go-style channels for concurrency
- Error Handling - Creating and handling structured errors
- OS Time - System time functions