← All languages

Servirtium for

Lua (Lua 5.4 C extension)

No shipped package: vendor the binding's source at a release tag, with the native library from the release. Release v2.0.0-alpha.20.

FFI mechanism
hand-written Lua 5.4 C extension linked against the library. csrc/servirtium.c is compiled once into servirtium_native.so, which links libservirtium_vcr and wraps its C ABI; servirtium.lua adds the chainable builders and the Server object. Not LuaJIT FFI.
Toolchain
Lua 5.4 with headers (pkg-config --cflags lua5.4 must work; Lua 5.1 and 5.5 will not load a 5.4 module) and a C compiler.
Distribution
Two source files at the tag, compiled against the release native library
Finding the library
Linked, not dlopen-ed: the extension is built with -lservirtium_vcr and an rpath of $ORIGIN (Linux) or @loader_path (macOS), so keep servirtium_native.so and libservirtium_vcr beside each other. SERVIRTIUM_VCR_LIB has no effect.
On GitHub
lua/ · README

Getting it

There is no published package for Lua (Lua 5.4 C extension). You vendor the binding's source into your project at the release tag v2.0.0-alpha.20 and take the native library from the same release.

  1. Fetch the native library for your OS/arch, verify its checksum, and give it the plain name the linker wants. Windows is not covered.
    TAG=v2.0.0-alpha.20
    REL=https://github.com/servirtium/servirtium-vcr/releases/download/$TAG
    case "$(uname -s)" in
      Linux)   OS=linux;   EXT=so;    ldd --version 2>&1 | grep -qi musl && LIBC=-musl || LIBC= ;;
      Darwin)  OS=macos;   EXT=dylib; LIBC= ;;
      FreeBSD) OS=freebsd; EXT=so;    LIBC= ;;
    esac
    case "$(uname -m)" in x86_64|amd64) ARCH=x86_64 ;; arm64|aarch64) ARCH=arm64 ;; esac
    LIBDIR="$HOME/.servirtium-vcr/$TAG"; mkdir -p "$LIBDIR"
    LIB=libservirtium_vcr-$TAG-$OS-$ARCH$LIBC.$EXT
    curl -fsSL -o "$LIBDIR/$LIB" "$REL/$LIB"
    curl -fsSL -o "$LIBDIR/$LIB.sha256" "$REL/$LIB.sha256"
    ( cd "$LIBDIR" && { sha256sum -c "$LIB.sha256" || shasum -a 256 -c "$LIB.sha256"; } )
    cp "$LIBDIR/$LIB" "$LIBDIR/libservirtium_vcr.$EXT"
    
  2. macOS only: the release .dylib carries a CI build path as its install name, so require 'servirtium' fails with 'Library not loaded: /home/runner/...'. Rewrite the install name and re-sign before building the extension.
    install_name_tool -id @rpath/libservirtium_vcr.dylib "$LIBDIR/libservirtium_vcr.dylib"
    codesign -f -s - "$LIBDIR/libservirtium_vcr.dylib"
    
  3. Fetch the two sources of the same tag and build the extension next to a copy of the library (use the Lua 5.4 headers; on Homebrew set PKG_CONFIG_PATH to lua@5.4's lib/pkgconfig).
    RAW=https://raw.githubusercontent.com/servirtium/servirtium-vcr/v2.0.0-alpha.20
    mkdir -p servirtium-lua
    curl -fsSL -o servirtium-lua/servirtium.lua $RAW/lua/servirtium.lua
    curl -fsSL -o servirtium-lua/servirtium.c   $RAW/lua/csrc/servirtium.c
    cp "$LIBDIR/libservirtium_vcr.$EXT" servirtium-lua/
    case "$(uname -s)" in
      Darwin) cc -O2 -shared -fPIC -undefined dynamic_lookup $(pkg-config --cflags lua5.4) servirtium-lua/servirtium.c \
                -Lservirtium-lua -lservirtium_vcr -Wl,-rpath,@loader_path -o servirtium-lua/servirtium_native.so ;;
      *)      cc -O2 -shared -fPIC $(pkg-config --cflags lua5.4) servirtium-lua/servirtium.c \
                -Lservirtium-lua -lservirtium_vcr -Wl,-rpath,'$ORIGIN' -o servirtium-lua/servirtium_native.so ;;
    esac
    
  4. Put both on the Lua search paths and run with lua5.4 (not whatever 'lua' is). Check it by replaying the canonical tape (expect 'ok-body (clean match)').
    export LUA_PATH="$PWD/servirtium-lua/?.lua;;" LUA_CPATH="$PWD/servirtium-lua/?.so;;"
    mkdir -p tapes
    curl -fsSL -o tapes/single_get.md $RAW/lua/tapes/single_get.md
    lua5.4 -e '
    local servirtium = require("servirtium")
    local srv = assert(servirtium.playback("tapes/single_get.md"):port(0):start())
    local body = io.popen("curl -s " .. srv:base_url() .. "/ok"):read("*a")
    print(body, srv:last_kind() == servirtium.OK and "(clean match)" or "(MISMATCH)")
    srv:close()'
    

Record

Point your client at the VCR's base URL; the VCR forwards to the real service and hands back the real response. Nothing is written until you commit.

local servirtium = require("servirtium")

local srv = assert(servirtium.record("tapes/climate_api.md",
                                     "https://climatedataapi.worldbank.org")
    :port(0):start())

io.popen("curl -s " .. srv:base_url() .. "/api/v1/countries"):read("*a")

-- commit writes the markdown tape and returns "" on success
assert(srv:commit() == "")

Playback

The same tape, replayed with no network.

local servirtium = require("servirtium")

local srv = assert(servirtium.playback("tapes/climate_api.md"):port(0):start())
local body = io.popen("curl -s " .. srv:base_url() .. "/api/v1/countries"):read("*a")

assert(srv:last_kind() == servirtium.OK, srv:last_error())   -- optional: clean match
srv:close()

Idiomatic extras

Discard when the test fails

close on a recording that was neither committed nor discarded writes nothing and returns the reason; discard drops it on purpose.

local srv = assert(servirtium.record(tape, upstream):port(0):start())
local ok, err = pcall(function()
    -- ... drive the SUT, assert on it ...
end)
if ok then assert(srv:commit() == "") else srv:discard(); error(err, 0) end

Redact credentials

redact_credentials scrubs the standard credential headers from the tape; redact_header, redact_query_param and redact_json_field cover named ones.

local srv = assert(servirtium.record(tape, upstream)
    :redact_credentials()
    :redact_json_field("secretKey")
    :port(0):start())

Volatile values and drift detection

Rules tokenise values that change on every run so a re-record is byte-identical; fail_if_changed makes commit return a message only on real drift.

local srv = assert(servirtium.record(tape, upstream)
    :volatile_rule("response headers", "Date: {{serverDate}}")
    :volatile_rule("request path", "/orders/(?<orderId>[0-9a-f]{16})", "regex")
    :fail_if_changed()
    :port(0):start())
-- ... drive SUT ...
local err = srv:commit()   -- the fresh tape is still written; err is non-empty on drift
if err ~= "" then error(err) end

Gotchas

  • Builders raise a Lua error on a refused rule; start() returns nil, message on failure; commit/close/discard return '' on success or the message.
  • The interpreter must be the one the extension was built for: lua5.4. A mismatch reads 'version mismatch: app. needs 504.0, Lua core provides 505.0'.
  • keep servirtium_native.so and the library together (the rpath is $ORIGIN / @loader_path). No LuaRocks package and no rockspec exist.
  • Use the -musl asset on Alpine. Rebuild the extension if you change the library; use the same tag for both.

Prompt for your coding agent

Paste this into Claude, Codex, Gemini or any coding agent, in your Lua (Lua 5.4 C extension) project. It wraps one of your existing integration tests with Servirtium. The general prompt has a slot for the language instead.

Hey Gemini or Claude or Codex,

I want a test in this Lua (Lua 5.4 C extension) project to run without calling a real web service every time. Use Servirtium (https://servirtium.dev), which records HTTP conversations as readable Markdown "tapes" and replays them. Do these steps in order and tell me what you did at each one.

1. Find an existing integration test in this project that calls a web service as a side effect of what it is testing. Prefer one that is slow, flaky, or needs credentials or network because of that call. Tell me which test you chose and why.

2. Add the Servirtium binding for Lua (Lua 5.4 C extension). Follow https://servirtium.dev/languages/lua/ exactly. Servirtium ships no package for this language. Vendor the binding's source into the project at the release tag v2.0.0-alpha.20 and put the native library from the same release where the page says: Two source files at the tag, compiled against the release native library.
   Toolchain and minimum version: Lua 5.4 with headers (pkg-config --cflags lua5.4 must work; Lua 5.1 and 5.5 will not load a 5.4 module) and a C compiler..
   How the binding finds the native library: Linked, not dlopen-ed: the extension is built with -lservirtium_vcr and an rpath of $ORIGIN (Linux) or @loader_path (macOS), so keep servirtium_native.so and libservirtium_vcr beside each other. SERVIRTIUM_VCR_LIB has no effect.

3. Route that test's HTTP client to the Servirtium VCR's base URL instead of the real service, using the idiomatic Lua (Lua 5.4 C extension) way of setting a base URL or HTTP client. The VCR starts on its own port (use port 0, so it picks a free one) and gives you its base URL; give that URL to the client and never hard-code a port.

4. Run the test once in record mode against the real service. Commit the recording when the test passes and discard it when the test fails: a record VCR that is closed without a commit or a discard writes no tape and raises an error. Use redact_credentials (the spelling for Lua (Lua 5.4 C extension) is on the page) so secrets become numbered tokens, and remove volatile request headers such as User-Agent and Date from the tape so playback does not depend on them.

5. Keep the tape beside the test as readable Markdown, in version control. Open it and check there are no secrets or personal data in it before committing.

6. Make the test play back by default, with an explicit switch (for example an environment variable such as SERVIRTIUM_RECORD=1) that re-records.

7. Prove it works offline: make the real service unreachable (network off, or a wrong host) and show the test still passes in playback.

Traps to avoid:
- A record VCR needs Commit() or Discard(); closing it without either writes nothing and raises.
- The VCR runs in your test process on its own port; the system under test must use the VCR's base URL, not the real one.
- Builders raise a Lua error on a refused rule; start() returns nil, message on failure; commit/close/discard return '' on success or the message.
- The interpreter must be the one the extension was built for: lua5.4. A mismatch reads 'version mismatch: app. needs 504.0, Lua core provides 505.0'.
- keep servirtium_native.so and the library together (the rpath is $ORIGIN / @loader_path). No LuaRocks package and no rockspec exist.
- Use the -musl asset on Alpine. Rebuild the extension if you change the library; use the same tag for both.

References:
- This language's page: https://servirtium.dev/languages/lua/
- The binding's directory: https://github.com/servirtium/servirtium-vcr/tree/main/lua
- Concepts, features and every language's quick start: https://servirtium.dev/llms-full.txt (index: https://servirtium.dev/llms.txt)

How these snippets were checked

Ran the Getting-it steps on cachyos (Linux x86_64, Lua 5.4.9, cc) with the sha256-checked release .so and the two sources of the tag: playback (ok-body, clean match), record + commit() == '' + replay (hello-upstream, OK), discard() leaves no tape, close() without commit returns the 'closed without commit or discard' message and writes nothing, redact_credentials in the record. Also built and loaded the extension on macOS arm64 with Homebrew lua@5.4 and the playback check passed after the install-name fix; without it require fails as described. The volatile/fail_if_changed extra is from docs and not run.

They mirror these files in the repository:

See also the feature reference, llms.txt and the lua/ directory.