Lua Script extension functions

The Lua Script policy provides extension functions and preset global variables for manipulating assembly context, messages, and variables.

Supported Lua standard library

All functions defined in the Lua 5.1 standard library are supported except:

  • collectgarbage
  • dofile
  • load
  • loadfile
  • loadstring
  • io.*
  • os.execute, os.exit, os.getenv, os.remove, os.rename, os.setlocale, os.tmpname
  • debug.*

In addition to the Lua 5.1 standard library, some LuaJIT functions are supported:

Preset global variables

The following global variables are preset and available in Lua scripts:

  • context: The assembly context object to access messages and variables
  • buffer: Provides functions to create Buffer objects
  • json: Provides functions to encode/decode JSON objects
  • console: Provides functions for message logging

Context

The Context object is preset in the global table with the name context. Use it to manipulate the assembly context, including messages and variables.

Method Description
get(name) Get a context variable by name. Returns the value (boolean, number, string, table, or nil).
set(name, value) Set a context variable. The value can be boolean, number, string, table, or nil.
get_message(name) Get a message object by name. Returns nil if the message does not exist.
create_message(name, is_request) Create a message object if it does not exist. Set is_request to false to create a response message.
run_action(name) Run an action defined in the actions property of the current luaScript action.

Example:

-- Get and set context variables
var1 = context:get('var1')
context:set('var1', { foo = '1', bar = true })

-- Work with messages
local req = context:get_message('request')
local resp = context:create_message('response')

-- Run actions
context:run_action('set-var-1')
context:run_action('my-invoke')

Note: Not all actions can be called in luaScript. For the list of valid actions, see the Options for actions table in the LuaScript policy documentation.

Message

The Message object represents a message in the assembly context.

Property Description
status The HTTP status code of the message (read/write).
status_text The HTTP status reason phrase of the message (read-only).
headers The headers object of the message. Can be manipulated using Headers API or replaced with a table.
body The body object of the message. Use Body API to access message body.

Example:

local request = context:get_message("request")
local response1 = context:create_message("response1")
local response2 = context:create_message("response2")

response1.status = 244
response2.status = response1.status
response1.headers = request.headers
response2.headers = {
  ["Content-Type"] = "application/pdf",
  ["Content-Disposition"] = "filename=abc.pdf",
  ["multi-values-header"] = {"value1", "value2"}
}

Headers

The Headers object provides methods to manipulate message headers.

Method Description
get(name) Get a header value by name. Returns the header value as a string, or nil if not found.
set(name, value) Set a header value. If value is nil, the header is deleted. Use a table for multiple values.

Example:

local request = context:get_message("request")

-- Get header value
local foo = request.headers:get('Foo')
local same_header1 = request.headers["foo"]
local same_header2 = request.headers.foo

-- Set header value
request.headers:set('Foo', 'bar')
request.headers['foo'] = 'bar'
request.headers.FOO = 'bar'

-- Set multiple values
request.headers['multi-values'] = {"foo", "bar"}

Body

The Body object provides methods to manipulate message body content.

Method Description
read() Get the value of the body. Returns boolean, number, string, table, Body, Buffer, or nil. Throws an error if the message is not loaded or parsed.
write(value) Write a value to the message body. Value can be boolean, number, string, table, Body, Buffer, or nil.
extract(expr) Extract content from the body using a JSONata expression. Returns the extracted value. Throws an error if expression is invalid or message is not loaded/parsed.
redact(expr) Redact content in the body using a JSONata path expression. Throws an error if expression is invalid or message is not loaded/parsed.
remove(expr) Remove content from the body using a JSONata path expression. Throws an error if expression is invalid or message is not loaded/parsed.

Example:

local request = context:get_message("request")
local req_body = request.body:read()

local response = context:create_message("response1")
response.body:write(req_body)
response.body:write(request.body)
response.body:write({foo = {bar = "baz"}})

local result = response.body:extract("foo.bar")

buffer

The buffer object is preset in the global table with the name buffer. It provides functions to create Buffer objects.

Function Description
create(size) Create a Buffer object with the specified size (unsigned integer).
from_string(str) Create a Buffer object from a string.

Example:

local buff1 = buffer:create(2048)
local buff2 = buffer:from_string('Hello world')

Buffer

The Buffer object is used for non-parsed message bodies or created directly from Lua.

Method Description
len() Return the length of the buffer.
concat(value) Concatenate a value (string, Buffer, or Body) to the buffer. Returns self. Throws an error if value is a parsed Body.
resize(len) Resize the buffer to the specified size in bytes. New bytes are initialized to 0. Returns self.
slice(start, end) Return a partial copy of the Buffer. Start is 1-based index. End is optional (defaults to buffer length).
tostring() Convert the buffer to a Lua string.

The Buffer object also provides methods for reading and writing integers at specific offsets:

  • readi8(offset), readi16be(offset), readi16le(offset), readi32be(offset), readi32le(offset) - Read signed integers
  • readu8(offset), readu16be(offset), readu16le(offset), readu32be(offset), readu32le(offset) - Read unsigned integers
  • writei8(offset, value), writei16be(offset, value), writei16le(offset, value), writei32be(offset, value), writei32le(offset, value) - Write signed integers
  • writeu8(offset, value), writeu16be(offset, value), writeu16le(offset, value), writeu32be(offset, value), writeu32le(offset, value) - Write unsigned integers

Note: Array subscript notation can be used for readu8 and writeu8:

local buff = buffer.from_string("Hello world")
local c = buff:readu8(2)
c = buff[2]  -- same effect
buff:writeu8(2, 69)
buff[2] = 69  -- same effect

json

The json object is preset in the global table with the name json. It provides functions to decode and encode JSON objects.

Function Description
decode(json_str) Decode a JSON string into a Lua table. Throws an error if the string is invalid JSON.
encode(value, pretty) Encode a value (boolean, number, string, or table) into a JSON string. Set pretty to true for pretty-printing (default is false). Throws an error if value is not a valid JSON object.

Example:

local obj = json.decode('{"foo": { "bar": true }}')
local str = json.encode({
  foo = {
    bar = true
  }
})

console

The console object is preset in the global table with the name console. It provides functions for message logging with different levels of verbosity.

Function Description
error(format, ...args) Log a message with error level.
warn(format, ...args) Log a message with warn level.
info(format, ...args) Log a message with info level.
debug(format, ...args) Log a message with debug level.
trace(format, ...args) Log a message with trace level.

Note: If the format parameter contains specifiers defined in string.format(), then string.format() is used to construct the formatted string. Otherwise, all parameters are joined with spaces.

Example:

console.info("Hello, world!")  -- Hello, world!
console.error("Hello %s", "world!")  -- Hello, world!
console.warn("Hello,", "world!")  -- Hello, world!
console.debug("Hello,", "world!", true, {foo = true})  -- Hello, world! true table: 0x7fedb801e960