Base Built-in Library

The base library provides core runtime functionality, error handling, protected calls, type introspection, and metatable control, loaded into the global scope by default.

Function Reference

Function Signature Description
print(...) (...) → void Converts arguments to strings using tostring() and writes them separated by tabs to stdout.
assert(v, [msg]) (val, [string]) → val Raises an error with msg (or "assertion failed!") if v evaluates to nil or false.
error(msg, [level]) (string, [int]) → none Terminates the active function and raises an uncaught runtime error at call stack depth level.
pcall(f, ...) (func, ...) → (bool, ...) Calls function f in protected mode. Catches any errors without crashing. Returns true, results... on success, or false, error_msg on failure.
xpcall(f, msgh, ...) (func, errHandler, ...) → (bool, ...) Protected call that invokes msgh with the error object before the stack is unwound (enables debug.traceback).
type(v) (any) → string Returns the type name: "nil", "number", "string", "boolean", "table", "function", "thread", or "userdata".
tostring(v) (any) → string Converts any value to a human-readable string representation, invoking the __tostring metamethod if defined.
tonumber(e, [base]) (any, [int]) → number|nil Converts an expression or string into a number. Supports optional radix from 2 to 36.
select(idx, ...) (int|"#", ...) → any If idx is "#", returns the total argument count. Otherwise, returns all arguments starting from position idx.
pairs(t) (table) → (iter, t, nil) Returns the triple next, t, nil to iterate through all key-value entries in a table.
ipairs(t) (table) → (iter, t, 0) Iterates through consecutive numerical integer keys from 1 to the first nil element.
setmetatable(t, mt) (table, table|nil) → table Attaches a metatable to table t. Pass nil to remove the metatable.
getmetatable(obj) (any) → table|nil Returns the attached metatable, or nil if no metatable exists.
rawget(t, k) (table, any) → any Reads t[k] directly without triggering the __index metamethod.
rawset(t, k, v) (table, any, any) → table Sets t[k] = v directly without triggering the __newindex metamethod.

Protected Calls & Error Handling Example

error_handling.lua
function riskyOperation(dividend, divisor) {
    if (divisor == 0) {
        error("Division by zero exception!")
    }
    return dividend / divisor
}

-- Safe execution with pcall:
success, result = pcall(riskyOperation, 10, 0)

if (not success) {
    print("Caught error safely: " .. result)
} else {
    print("Result: " .. result)
}