# How to write a new language generator for a Lua SDK

> Write the Lua mapping down, emit it as your own sdkgen target with a pluggable transport and a rockspec, and prove it on Lua 5.1 and 5.4 against recorded replies.

Source: https://voxgig.com/howto/write-a-new-language-generator-for-lua

- Audience: library-maintainer
- Level: advanced
- Languages: lua, typescript
- Verified: 2026-11-20
- Published: 2026-11-20

## Short answer

In sdkgen, add a target of your own. Give it a model file under `.sdk/model/target/`, a `Main` component that turns each operation into a Lua function returning `data, err`, and a one-function transport bound to LuaSocket. Emit a rockspec that pins `lua >= 5.1, < 5.5`, generate twice, compare the bytes, and run the client on each interpreter.

---
## You will need

Node 22 or later, an OpenAPI 3 document, and every interpreter you intend to claim. This page
uses the Bookshelf document and runs the client on Lua 5.4.6 and on Lua 5.1.5 built from
[lua.org](https://www.lua.org/manual/5.1/manual.html), the version
[LuaJIT's extensions page](https://luajit.org/extensions.html) calls LuaJIT fully upwards-compatible
with. Read the prerequisite on third-tier targets first.

sdkgen 4.44.3 bundles a `lua` target: entity-shaped, with `nil, err` returns and LuaSocket
behind `utility.fetcher`. This page adds a second target, `lua-lite`, because the runtime range
is the thing that does not fit.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [OpenAPI Generator lua generator](https://openapi-generator.tech/docs/generators/lua/) | Lua 5.2 or later with `lua-http`, and one function per endpoint suits callers | A beta generator, reshaped by overriding its Mustache templates rather than through a mapping | OpenResty, Lua 5.1, or entity-shaped calls |
| [OpenAPI Generator meta command scaffolding](https://openapi-generator.tech/docs/customization/) | A team that already maintains Java generators and wants full control | Rebuilds the language layer from a Java class, and the parser's naming stays operationId-driven | You want the operations already grouped and typed |
| [orval](https://orval.dev/docs/reference/configuration/output/) | Your other clients are TypeScript and Lua is the one gap | No Lua output at all, so Lua needs a second generator beside it | Lua is the main target |
| [the sdkgen custom target route](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/author-a-new-language.md) | Several targets from one model, and you will own one more | Ties your target to sdkgen's model shape, and doctor flags your target's own files | You want a standalone generator with no upstream |

Voxgig maintains sdkgen. It is the subject of this page and one of four options in the table,
not the recommendation.

Reusing sdkgen's model saves the parsing and the classification, and ties the target to that
model's shape. A `meta` generator owes nothing to sdkgen and rebuilds the language layer in
Java. orval writes TypeScript only, so it is a neighbor here, not a route.

## Write the language mapping down first

Decide each of these before writing a line of the component. The component then encodes them,
and `mapping.ts` keeps the reusable ones testable on their own.

- Type names: `$STRING`, `$INTEGER`, `$NUMBER` and `$BOOLEAN` become `string`, `integer`,
  `number` and `boolean` in Lua language server `---@field` annotations.
- Reserved words: the 22 of Lua 5.4.[^1] A name that is one, or is not an identifier, is
  indexed, `Client["end"]`, never written `Client.end`.
- String escaping: every emitted literal escapes quote, backslash, control bytes and bytes
  over 126 as three-digit `\ddd`, which Lua 5.1 already reads.
- Module naming: one module named after the project, `bookshelf`, and its runtime under it,
  `bookshelf.json` and `bookshelf.luasocket`.
- Returns: every operation returns `data, err` and never raises; `err.kind` is `param`, `http`,
  `transport`, `encode` or `decode`.
- Transport: `transport(request)` returns `response, err`, with plain tables on both sides.

## Emit the client from the model

The target's model file switches every standard phase off, as a tool target does, so `Main`
writes the whole package. Each operation reaches the component already classified, with its
path split into literal and variable segments:

```ts title=".sdk/src/cmp/lua-lite/Main_lua-lite.ts"
        const arg = point.bf ? 'data' : 'match'
        const parts: string[] = []
        const checks: string[] = []
        for (const s of point.s || []) {
          if (null != s.lit) parts.push(luastr('/' + s.lit))
          else {
            const v = '_' + s.var.replace(/[^A-Za-z0-9_]/g, '_')
            checks.push(`  local ${v}, ${v}_err = segment(${arg}[${luastr(s.var)}], ${luastr(s.var)})\n` +
              `  if not ${v} then return nil, ${v}_err end\n`)
            parts.push(luastr('/'), v)
          }
        }
```

What it writes for `GET /books/{bookId}`:

```lua title="generated/lua-lite/bookshelf.lua"
Book.load = function(self, match)
  match = match or {}
  local _id, _id_err = segment(match["id"], "id")
  if not _id then return nil, _id_err end
  return self.client:call("GET", "/books" .. "/" .. _id, nil)
end
```

The model already renamed `bookId` to `id`, so every target's callers write `load({ id = ... })`.
`segment` percent-encodes the value and refuses `""`, `.` and `..` before any request.

## Bind the transport and emit a rockspec

The component copies two runtime files: a JSON encoder and decoder in Lua 5.1 syntax, so the client needs no
JSON rock, and the LuaSocket binding. The binding calls
[`socket.http.request`](https://lunarmodules.github.io/luasocket/http.html) with an `ltn12`
source and sink, and switches to LuaSec's `ssl.https` for an `https` URL. The rockspec pins one
interpreter range, LuaSocket, and LuaSec, using the special `lua` dependency the
[rockspec format](https://github.com/luarocks/luarocks/blob/main/docs/rockspec_format.md)
reserves for the interpreter version:

```lua title="generated/lua-lite/bookshelf-lite-0.0.1-1.rockspec"
dependencies = {
  "lua >= 5.1, < 5.5",
  "luasocket >= 3.0",
  "luasec >= 1.0",
}
```

## Run it against a recorded response

`client_test.lua` builds a client with a transport that records each request and replies from
the files in `recorded/`, then checks each part of the mapping.

```bash
lua5.4 client_test.lua
```

```text output
ok   list returns the recorded book: Emma
ok   published decodes as a number: 1815
ok   a 404 is nil, err with status 404
ok   an id is one escaped segment: https://api.example.com/v1/books/b%2F1
ok   an id of .. is refused before any request: param
ok   an empty id and an id of . are refused too: param param
ok   create sends JSON: {"published":1817,"title":"Persuasion"}
ok   a transport failure is returned, not raised: connection refused
Lua 5.4, all checks passed
```

`generate.sh` ran the same file on Lua 5.1.5 and kept its output in `generated/run-lua5.1.txt`;
its last line is `Lua 5.1, all checks passed`.

## Compare the OpenAPI Generator Lua client and the orval options

OpenAPI Generator 7.27.0 printed `Generator 'lua' is considered beta` for the same document.
`inspect.mjs` reads both clients.

```bash
node inspect.mjs
```

```text output
sdkgen lua-lite
  calls:    Client.book Book.create Book.list Book.load Book.remove Book.update M.new Client:call
  requires: bookshelf.json bookshelf.luasocket
  rockspec: lua >= 5.1, < 5.5 | luasocket >= 3.0 | luasec >= 1.0
  one book: self.client:call("GET", "/books" .. "/" .. _id
OpenAPI Generator lua
  calls:    default_api:create_book default_api:delete_book default_api:get_book default_api:list_books default_api:update_book
  requires: http.request http.util dkjson basexx openapiclient.model.book
  rockspec: lua >= 5.2 | http | dkjson | basexx
  one book: string.format("%s/books/%s", self.basePath, book_id)
generate run 1: 112 files, run 2: 112 files, byte changes: 0
```

Its `get_book` formats `book_id` into the path without escaping it, so an id of `b/1` asks for
a different path. Its version floor is a template, not Java. `author template -g lua` writes the
built-in templates, the `lua >= 5.2` line sits in `luarocks.mustache`, and `generate -t` with an
edited copy wrote `lua >= 5.1, < 5.5`, the user-defined templates route
[OpenAPI Generator's customization page](https://openapi-generator.tech/docs/customization/)
describes. Replacing `lua-http` means rewriting `api.mustache` too, and a `meta` generator class
is the step past that.

orval has no Lua output. Its `client` option takes seventeen values, from `angular` to `mcp`, all
TypeScript output, or a function that builds a client from orval's own generators. A team that
keeps orval for its TypeScript client generates the Lua one from the same document with either
route on this page.

## Check it worked

Generate twice from a clean scaffold and compare every output byte, then run the client. The
last line of the `inspect.mjs` output is the first half, and a second scaffold built from
scratch wrote the same 112 fingerprints. The tests cover the rest.

```bash
node --test lua.test.mjs
```

```text output
# tests 7
# suites 0
# pass 7
# fail 0
```

One test runs `lua5.4` and fails unless it prints `Lua 5.4, all checks passed`. Another emits a
string with a quote, a backslash, a newline before a digit and an accented letter, and checks
Lua reads it back unchanged.

## When it goes wrong

A literal reads back wrong. A decimal escape without padding, `\10` before a `5`, reads as
`\105`, the letter `i`. Pad every escape to three digits, as `luastr` does.

The client fails on the first user's runtime. Lua 5.1 has no `goto`, no `//` and no `utf8`
library, so the runtime files are written in 5.1 syntax and the rockspec says so. Under
OpenResty, pass a transport built on its cosocket API rather than the LuaSocket binding.

The target writes an endpoint function where the model holds an entity. Read `point.s` and the
op name from the model; parsing the path again in the component rebuilds what apidef did.

## When not to do this

Do not write your own target if the bundled sdkgen `lua` target fits your interpreter. It
carries the full pipeline, features and test corpus, which `lua-lite` does not.

Leave sdkgen out if Lua is your only client. The OpenAPI Generator `lua` generator is
the better choice on Lua 5.2 or later with `lua-http`, and a hand-written client is smaller
still for a handful of endpoints.

Do not claim OpenResty until you have run the client inside it.[^2] This page ran Lua 5.1.5, the dialect
LuaJIT follows, and not LuaJIT itself.

## Related how-tos

- [Evaluate a third-tier SDK target before you ship it](/howto/evaluate-a-third-tier-sdk-target)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Generate a code section with code instead of a template](/howto/generate-a-code-section-with-a-component)

- [Wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)

- [Package a customization several SDK projects can install](/howto/package-a-shared-generator-customisation)

## Last verified

Verified 2026-11-20 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, OpenAPI Generator 7.27.0, Lua 5.4.6 and Lua 5.1.5. Every output block is what the
command preceding it printed. Generation ran in `generate.sh`, including OpenAPI Generator with
an overridden `luarocks.mustache`. OpenResty and LuaJIT were not
run, LuaSocket and LuaSec were not installed, so the binding was not exercised, and orval was
not run because it has no Lua output.

[^1]: The [Lua 5.1 manual](https://www.lua.org/manual/5.1/manual.html) reserves 21 words. The
[Lua 5.2 manual](https://www.lua.org/manual/5.2/manual.html) adds `goto`, so a 5.1 program with
a variable of that name stops parsing on every later Lua. The mapping reserves all 22, which
costs a 5.1 caller one name: a field called `goto` is indexed as `["goto"]`.

[^2]: The [lua-nginx-module README](https://github.com/openresty/lua-nginx-module) says the
module embeds LuaJIT 2.0 or 2.1 and is a core component of OpenResty. Since its version
`v0.10.16` the standard Lua interpreter, PUC-Rio Lua, is not supported, so a client tested
only on PUC-Rio Lua has not met the interpreter OpenResty runs.