Skip to main content

Script Globals

script.globals

Values and functions available in every script without requiring any module: the script's input payload, the current node directory, and stdlib-style helpers for loading modules and debug printing.


Data​

field

Data

The inbound message/request payload.

The inbound message/request payload passed to main(Data). For Source HTTP nodes this is the raw HTTP request text; for Transform/LLP nodes it is the message body.

Usage

local raw = Data

Returns

  • string — the raw inbound payload.

Example

local Raw = Data
print(#Raw)

__node_dir​

field

__node_dir

Deprecated. Filesystem path to the current node directory - use linkiir.sys.nodeDir().

Deprecated: use linkiir.sys.nodeDir() instead. The filesystem path to the current node directory, still set before the script runs.

Usage

local nodeDir = linkiir.sys.nodeDir()

Returns

  • string — absolute path to the node directory.

Example

-- Deprecated form:
local SchemaPath = __node_dir .. '/demo.json'

-- Current form - relative schema paths resolve against the node directory:
local Msg = linkiir.data.extract{ schema = 'demo.json', data = Data }

require​

function

require(modname)

Load a Lua module.

Loads a Lua module. Search path: node dir (including any linked library dependencies, staged there at run time), then the project's common/ dir (shared modules), then system defaults.

Usage

local mod = require "modname"

Parameters

NameTypeRequiredDescription
modnamestringYesModule name (e.g. "legacy_adapter").

Returns

  • module table

Errors

Raises a Lua error when the module cannot be found.

Example

local Adapter = require('legacy_adapter')
Adapter.transform(Data)

print​

function

print(...)

Print values to stdout.

Prints values to stdout, prefixed with the node ID.

Usage

print(Msg:name(), Msg:count())

Parameters

NameTypeRequiredDescription
...anyNoValues to print (variadic).

Returns

  • nil

Example

print('processing', linkiir.sys.guid(128))

trace​

function

trace(...)

Pretty-print values to stdout.

Pretty-prints values to stdout (legacy debug trace). Recursively expands tables.

Usage

trace(SomeTable)

Parameters

NameTypeRequiredDescription
...anyNoValues to pretty-print (variadic).

Returns

  • nil

Example

trace({ id = 1, items = { 'a', 'b' } })

type​

function

type(v)

Type name of a value.

Returns the type of its only argument, coded as a string: "nil", "boolean", "number", "string", "table", "function", "thread", or "userdata".

Usage

type(v)

Parameters

NameTypeRequiredDescription
vanyYesValue to inspect.

Returns

  • string

Example

print(type(Data)) -- "string"
print(type(nil)) -- "nil"
print(type({})) -- "table"

tostring​

function

tostring(v)

Convert a value to a printable string.

Receives a value of any type and converts it to a string in a reasonable format.

Usage

tostring(v)

Parameters

NameTypeRequiredDescription
vanyYesValue to convert.

Returns

  • string

Example

print(tostring(42)) -- "42"
print(tostring(nil)) -- "nil"

tonumber​

function

tonumber(e [, base])

Convert a value to a number.

Converts a number or numeric string to a number, or returns nil. An optional base (2-36) reads it as an integer in that base.

Usage

tonumber(e, base)

Parameters

NameTypeRequiredDescription
eanyYesValue to convert.
baseintegerNoNumeric base (2-36) for string conversion.

Returns

  • number, or nil if the conversion fails

Example

print(tonumber('42')) -- 42
print(tonumber('2A', 16)) -- 42
print(tonumber('abc')) -- nil

pairs​

function

pairs(t)

Iterate all key/value pairs of a table.

Returns three values (next, t, nil) so that a generic for loop iterates over all key/value pairs of table t, in an undefined order.

Usage

for k, v in pairs(t) do ... end

Parameters

NameTypeRequiredDescription
ttableYesTable to iterate.

Returns

  • next, t, nil (for use in a generic for loop)

Example

local Headers = { ['Content-Type'] = 'text/plain', ['X-Id'] = '123' }
for k, v in pairs(Headers) do
print(k, v)
end

ipairs​

function

ipairs(t)

Iterate the array part of a table in order.

Returns three values so that a generic for loop iterates over the pairs (1, t[1]), (2, t[2]), ..., up to the first nil value.

Usage

for i, v in ipairs(t) do ... end

Parameters

NameTypeRequiredDescription
ttableYesTable (array) to iterate.

Returns

  • iterator function, t, 0 (for use in a generic for loop)

Example

local Files = linkiir.sys.fs.list{ path = '/inbound' }
for i, f in ipairs(Files) do
print(i, f)
end

next​

function

next(t [, k])

Low-level table iterator.

Returns the key/value pair after key k in table t, or the first pair when k is nil. Returns nil when there are no more; pairs() is built on it.

Usage

next(t, k)

Parameters

NameTypeRequiredDescription
ttableYesTable to iterate.
kanyNoPrevious key; omit to get the first pair.

Returns

  • nextKey, nextValue, or nil when exhausted

Example

local k, v = next(Headers)
while k do
print(k, v)
k, v = next(Headers, k)
end

select​

function

select(index, ...)

Count or pick from a variadic argument list.

If index is the string "#", returns the total number of extra arguments. Otherwise returns all arguments from index onward.

Usage

select(index, ...)

Parameters

NameTypeRequiredDescription
indexinteger|stringYes1-based position, or "#" for the count.
...anyNoVariadic arguments.

Returns

  • the selected arguments, or a count when index is "#"

Example

local function Count(...)
return select('#', ...)
end
print(Count('a', 'b', 'c')) -- 3
print(select(2, 'a', 'b', 'c')) -- "b" "c"

error​

function

error(message [, level])

Raise a Lua error.

Terminates the last protected function called (or the whole script) and returns message as the error object. level controls where position info is added (1 = the caller of error, the default).

Usage

error(message, level)

Parameters

NameTypeRequiredDescription
messageanyYesError value, usually a string.
levelintegerNoPosition-info level. Default 1.

Returns

  • does not return

Example

if not Resp then error('request failed') end

assert​

function

assert(v [, message])

Raise an error if v is falsy.

If v is false or nil, calls error(message), using "assertion failed!" as a default message. Otherwise returns all its arguments.

Usage

assert(v, message)

Parameters

NameTypeRequiredDescription
vanyYesValue to check.
messageanyNoError value used when v is falsy.

Returns

  • v, ... (all arguments, unchanged, when v is truthy)

Example

local Mrn = assert(Msg.PID[3][1][1]:value(), 'missing MRN')

pcall​

function

pcall(f, ...)

Call a function in protected mode.

Calls f with the given arguments in protected mode: any error inside f is caught instead of propagating. Returns true plus f's results on success, or false plus the error object on failure.

Usage

local ok, result = pcall(f, ...)

Parameters

NameTypeRequiredDescription
ffunctionYesFunction to call.
...anyNoArguments to pass to f.

Returns

  • true, results... on success
  • false, errorObject on failure

Example

local Ok, Msg, MsgType = pcall(linkiir.data.extract, { schema = 'demo.json', data = Data })
if not Ok then error('extract failed: ' .. tostring(Msg)) end

xpcall​

function

xpcall(f, msgh)

Call a function in protected mode with a message handler.

Like pcall, but calls the message handler msgh in the context of the error, before the stack unwinds — useful for attaching a traceback.

Usage

local ok, result = xpcall(f, msgh)

Parameters

NameTypeRequiredDescription
ffunctionYesFunction to call (no arguments).
msghfunctionYesMessage handler, called with the error object.

Returns

  • true, results... on success
  • false, handlerResult on failure

Example

local Ok, Err = xpcall(function() return riskyStep() end, debug.traceback)
if not Ok then print(Err) end

unpack​

function

unpack(list [, i [, j]])

Expand a table into multiple return values.

Returns the elements from the given table list, from list[i] to list[j]. Defaults are i = 1 and j = #list.

Usage

unpack(list, i, j)

Parameters

NameTypeRequiredDescription
listtableYesTable (array) to expand.
iintegerNoStart index. Default 1.
jintegerNoEnd index. Default #list.

Returns

  • the unpacked values

Example

local Args = { 'a', 'b', 'c' }
print(unpack(Args)) -- "a" "b" "c"

rawequal​

function

rawequal(v1, v2)

Compare two values without metamethods.

Checks whether v1 is equal to v2, without invoking the __eq metamethod.

Usage

rawequal(v1, v2)

Parameters

NameTypeRequiredDescription
v1anyYesFirst value.
v2anyYesSecond value.

Returns

  • boolean

Example

print(rawequal(1, 1)) -- true

rawget​

function

rawget(t, k)

Read a table field without metamethods.

Gets the real value of t[k], without invoking the __index metamethod.

Usage

rawget(t, k)

Parameters

NameTypeRequiredDescription
ttableYesTable to read.
kanyYesKey to read.

Returns

  • the raw value

Example

print(rawget(SomeTable, 'id'))

rawset​

function

rawset(t, k, v)

Write a table field without metamethods.

Sets the real value of t[k] to v, without invoking the __newindex metamethod. Returns t.

Usage

rawset(t, k, v)

Parameters

NameTypeRequiredDescription
ttableYesTable to modify.
kanyYesKey to set.
vanyYesValue to set.

Returns

  • t

Example

rawset(SomeTable, 'id', 42)

setmetatable​

function

setmetatable(t, metatable)

Attach a metatable to a table.

Sets the metatable for table t. Returns t.

Usage

setmetatable(t, metatable)

Parameters

NameTypeRequiredDescription
ttableYesTable to modify.
metatabletable|nilYesNew metatable, or nil to remove it.

Returns

  • t

Example

local Vector = setmetatable({ x = 1, y = 2 }, VectorMeta)

getmetatable​

function

getmetatable(t)

Read a table's metatable.

Returns the metatable of t, or nil if it has none (or the metatable's __metatable field, if that is set).

Usage

getmetatable(t)

Parameters

NameTypeRequiredDescription
tanyYesValue to inspect.

Returns

  • table, or nil

Example

local Meta = getmetatable(Vector)

collectgarbage​

function

collectgarbage([opt [, arg]])

Control the garbage collector.

Runs a garbage-collector action selected by opt, such as "collect", "count" or "step". With no arguments, runs a full collection.

Usage

collectgarbage(opt, arg)

Parameters

NameTypeRequiredDescription
optstringNoAction name. Default "collect".
arganyNoArgument for the selected action.

Returns

  • depends on opt (e.g. current memory use in Kbytes for "count")

Example

collectgarbage() -- full collection cycle
print(collectgarbage('count')) -- current memory use, in Kbytes

_VERSION​

field

_VERSION

The running Lua version string.

A global variable (not a function) holding a string with the running Lua version, e.g. "Lua 5.1".

Usage

print(_VERSION)

Returns

  • string

Example

print(_VERSION) -- "Lua 5.1"

_G​

field

_G

The global environment table.

The table representing the script's global environment. Reading/writing _G.x is equivalent to reading/writing the global variable x.

Usage

_G.SomeGlobal

Returns

  • table

Example

_G.Counter = 0
print(Counter) -- 0

dofile​

function

dofile([filename])

Execute a Lua file as a chunk.

Runs the Lua file filename in the global environment, with errors passed to the caller. Prefer require for reusable modules, since dofile re-runs the file on every call.

Usage

dofile(path)

Parameters

NameTypeRequiredDescription
filenamestringNoPath of the Lua file to run. Default stdin.

Returns

  • whatever the chunk returns

Example

dofile(linkiir.sys.nodeDir() .. '/helpers.lua')

loadfile​

function

loadfile([filename])

Load a Lua file without running it.

Loads a chunk from filename (or stdin, if omitted) without running it. Returns the compiled chunk as a function, or nil plus an error message on a syntax error.

Usage

local chunk, err = loadfile(path)

Parameters

NameTypeRequiredDescription
filenamestringNoPath of the Lua file to load. Default stdin.

Returns

  • function on success; nil, errorMessage on failure

Example

local Chunk, Err = loadfile(linkiir.sys.nodeDir() .. '/helpers.lua')
if Chunk then Chunk() end

loadstring​

function

loadstring(string [, chunkname])

Compile a Lua chunk from a string.

Compiles a chunk from a string without running it, returning it as a function, or nil and an error message. chunkname is used in error messages.

Usage

local chunk, err = loadstring(code)

Parameters

NameTypeRequiredDescription
stringstringYesLua source code.
chunknamestringNoName used in error messages/tracebacks. Default the string itself.

Returns

  • function on success; nil, errorMessage on failure

Example

local Chunk = loadstring('return 1 + 1')
print(Chunk()) -- 2

load​

function

load(func [, chunkname])

Compile a Lua chunk from a reader function.

Loads a chunk using func, a reader function repeatedly called with no arguments that must return successive pieces of the chunk's source (or nil/empty string to signal the end). Returns the compiled chunk as a function, or nil plus an error message on a syntax error.

Usage

local chunk, err = load(reader)

Parameters

NameTypeRequiredDescription
funcfunctionYesReader function returning successive source chunks.
chunknamestringNoName used in error messages/tracebacks.

Returns

  • function on success; nil, errorMessage on failure

Example

local Parts = { 'return ', '1 + 1' }
local I = 0
local Chunk = load(function() I = I + 1 return Parts[I] end)
print(Chunk()) -- 2

getfenv​

function

getfenv([f])

Read a function's environment table.

Returns the current environment table of f (a function, or a stack-level integer; default 1, the calling function).

Usage

getfenv(f)

Parameters

NameTypeRequiredDescription
ffunction|integerNoFunction, or stack level. Default 1.

Returns

  • table

Example

local Env = getfenv(1)

setfenv​

function

setfenv(f, table)

Set a function's environment table.

Sets the environment for the function f (a function, or a stack-level integer, where 1 means the calling function) to table. Returns f when f is a function.

Usage

setfenv(f, table)

Parameters

NameTypeRequiredDescription
ffunction|integerYesFunction, or stack level.
tabletableYesNew environment table.

Returns

  • f (when f is a function)

Example

local Sandbox = setmetatable({}, { __index = _G })
setfenv(SomeFn, Sandbox)

module​

function

module(name [, ...])

Create or enter a named module.

Lua 5.1's legacy module system: makes a module table named name the environment of the running function. Modern code returns a table from a chunk loaded with require instead.

Usage

module('mymodule')

Parameters

NameTypeRequiredDescription
namestringYesModule name.
...functionNoOptional module modifiers, e.g. package.seeall.

Returns

  • none

Example

module('mymodule', package.seeall)

function greet(name)
return 'hello, ' .. name
end