In the previous article, How to Run Lua Scripts in Nginx with OpenResty: Configuration, Common Uses, and Pitfalls, we ran our first Lua code from nginx.conf. When developers with experience in other languages start learning Lua for OpenResty and writing more realistic gateway logic, they often hit the same question: Do I need to work through a complete Lua tutorial first?

Working through a complete Lua tutorial is usually overkill: much of it covers concepts that rarely come up in gateway development. But writing OpenResty code purely on intuition from other languages can trip you up on several Lua-specific rules—and can even introduce production problems such as data leaking across requests or blocked worker processes.

This article is for readers who already know how to program. It does not teach if/else or loops from scratch. Instead, it covers the practical syntax and Lua basics you will use most when reading and writing OpenResty code, along with the pitfalls developers most often hit when they carry habits from other languages into OpenResty.

Quick Answer

You do not need to complete a general Lua course before writing OpenResty applications. Start with the Lua 5.1 syntax that LuaJIT implements, declare every variable inside request-handling code as local, learn tables and Lua truthiness, follow the res, err error-handling convention, distinguish nil from ngx.null, and avoid blocking standard-library I/O during request processing. That practical subset is enough to read and write ordinary OpenResty application code.

Which Lua Version Does OpenResty Use?

Before writing any code, make sure you know which Lua version you are targeting.

OpenResty does not use the standard Lua interpreter (PUC-Rio Lua). It maintains its own luajit2 branch; see LuaJIT in OpenResty: How It Works and How luajit2 Differs for details. LuaJIT is based on the Lua 5.1 language standard, with selected Lua 5.2 compatibility features and extensions such as ffi, bit, and table.new.

As a result, many modern Lua tutorials online—usually written for Lua 5.3 or 5.4—contain syntax that fails immediately in OpenResty:

  • No floor-division operator //: LuaJIT does not support this operator, which was introduced in Lua 5.3. Use math.floor(a / b) instead.
  • No native bitwise operators &, |, and ~: Lua 5.3 bitwise operators produce syntax errors in OpenResty. Use LuaJIT’s built-in bit library, for example local bit = require "bit" followed by bit.band or bit.bor.
  • No <const> or <close> attributes: These are Lua 5.4 syntax and cannot be used in OpenResty.

Two practical habits help you avoid version pitfalls:

  1. Use 5.1 documentation: For standard-library behavior, refer to the official Lua 5.1 reference manual, or use restydoc to read installed documentation from the terminal.
  2. State the runtime when using AI assistance: Many models default to Lua 5.3/5.4 syntax or standard-library calls that block. Add “The runtime is OpenResty / LuaJIT (based on Lua 5.1)” to your prompt to save a lot of time chasing syntax errors.

The Minimum Syntax You Need to Read the Next Article’s Code

The following concepts—especially where they differ from C, Java, Python, and JavaScript—are enough to read and write ordinary OpenResty application code.

Variables Need local

In many languages, a variable declared inside a function is local by default. In Lua, a variable without the local keyword is global by default.

-- Wrong: without local, user_id becomes a global variable.
user_id = ngx.var.arg_uid

-- Correct: explicitly declare a local variable.
local user_id = ngx.var.arg_uid

In an ordinary script, an accidental global may only pollute the namespace. In OpenResty, all requests handled by one Nginx worker share the same LuaJIT VM. If request data is accidentally written to a global, concurrent requests can overwrite one another’s value, causing serious cross-request data leakage. Treat this as a hard rule: declare every variable and helper function created during request processing as local. Define exported module functions as fields on a local module table, as shown later.

The nil and Truthiness Trap: 0 and "" Are Truthy

Lua uses nil to represent an absent or undefined value. Reading an unassigned variable or a missing table key gives you nil instead of raising an error.

Lua’s condition rules often surprise C, Python, and JavaScript developers: only false and nil are falsy; every other value is truthy, including the number 0 and the empty string "".

local count = 0
if count then
    -- This runs because 0 is truthy in Lua.
    ngx.say("count is truthy")
end

local name = ""
if name then
    -- This also runs because an empty string is truthy.
    ngx.say("empty string is also truthy")
end

To test for zero or an empty string, write the comparison explicitly: if count == 0 then or if name == "" then.

table: Lua’s Only Composite Data Structure

Lua has no separate array, map/dictionary, or class type. A table serves all of these roles.

  • Used as an array, a table is indexed from 1:
local upstreams = { "10.0.0.1:8080", "10.0.0.2:8080" }
ngx.say(upstreams[1]) -- Prints 10.0.0.1:8080
ngx.say(#upstreams)   -- Length operator #; prints 2

Lua standard-library functions and lua-resty-* libraries follow the same one-based indexing convention. Arrays are commonly traversed with for i = 1, #arr do or ipairs(arr).

  • As a dictionary or module container:
local config = {
    host = "127.0.0.1",
    port = 6379,
}
ngx.say(config.host)      -- Dot access; prints 127.0.0.1
ngx.say(config["port"])   -- Bracket access; prints 6379

Functions are first-class values in Lua and can be stored in tables. In the next article, where we write our own Lua module, you will see local _M = {} at the top of the file, functions attached to _M, and return _M at the end. In essence, this defines and returns a local table full of functions.

The Difference Between Dot . and Colon :

Some calls in OpenResty code use a dot, such as ngx.say("hello"), while others use a colon, such as red:get("key").

The colon is syntactic sugar for object-style method calls: obj:method(x) is exactly equivalent to obj.method(obj, x). It automatically passes the object before the colon as the first argument, conventionally named self inside the method.

  • Dot .: Calls a stateless module function, such as ngx.say() or cjson.encode(data).
  • Colon :: Calls a method that operates on an instance with state. With lua-resty-redis, for example, local red = redis:new() creates a connection object. The later red:connect(...) and red:get(...) calls operate on that specific red instance and therefore use colons. Writing red.get("key") instead passes "key" in the position where self belongs and causes an error at runtime.

String Concatenation .. and Inequality ~=

Two frequently used basic operators differ from many other languages:

  • Concatenate strings with two dots, .., not with +. Applying + to strings makes Lua try to convert them to numbers and add them; conversion failure raises an error.
local key = "user:" .. user_id
  • Write “not equal” as ~=, not !=:
if status ~= 200 then
    ngx.log(ngx.WARN, "unexpected status: ", status)
end

Multiple Return Values

Lua functions can natively return multiple values, and callers receive them in order with a comma-separated variable list:

local function parse_addr(addr)
    -- Assume the function parses and returns both host and port.
    return "127.0.0.1", 6379
end

local host, port = parse_addr("127.0.0.1:6379")

This feature appears throughout OpenResty because the ecosystem’s error-handling convention is built on multiple return values.

Error-Handling Convention: local res, err = ...

Developers coming from Java, Python, or JavaScript may instinctively look for try / catch. Lua does provide a similar pcall function, but many OpenResty APIs and lua-resty-* libraries do not throw an exception for ordinary operational failures such as a network timeout or refused connection. Instead, they return nil (or false) plus a detailed error string in err.

This pattern will be familiar to Go developers. The standard OpenResty pattern for making a call and handling its error looks like this:

local res, err = some_resty_call()
if not res then
    ngx.log(ngx.ERR, "failed to execute call: ", err)
    return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

This five-line pattern appears throughout OpenResty code:

  1. Receive the return values in local res, err.
  2. Check for failure with if not res then.
  3. On failure, write the specific err to Nginx’s error.log with ngx.log(ngx.ERR, ...), then stop the request and return an appropriate HTTP status with return ngx.exit(...).

Not every API follows this convention. JSON parsing is a common exception: cjson.decode() throws an error for invalid JSON instead of returning nil, err. To handle parse failures with the pattern above, use the cjson.safe module:

local cjson_safe = require "cjson.safe"

local data, err = cjson_safe.decode(body)
if not data then
    ngx.log(ngx.ERR, "failed to decode json: ", err)
    return ngx.exit(ngx.HTTP_BAD_REQUEST)
end

Watch Out: ngx.null Is Truthy

There is another classic edge case when using lua-resty-redis, lua-resty-mysql, or lua-cjson.

Lua tables cannot store nil values. To represent null values from a database (SQL NULL, or a missing Redis key) as well as JSON null, OpenResty provides a special light userdata constant: ngx.null.

Recall that only false and nil are falsy. ngx.null is neither false nor nil, so it is truthy in an if condition.

A complete and safe Redis lookup therefore needs two checks:

local val, err = red:get("session:1001")
if not val then
    -- Step 1: nil means the network operation or Redis command failed.
    ngx.log(ngx.ERR, "failed to get session from redis: ", err)
    return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

if val == ngx.null then
    -- Step 2: Communication succeeded, but the key does not exist.
    return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end

-- From here on, val holds the actual string value.

Why Must OpenResty Code Avoid Blocking Standard-Library I/O During Request Processing?

If you have written standalone Lua scripts or copied generic Lua code generated by AI, you may be tempted to use io.open, io.popen, or os.execute.

During request processing, this rule is absolute: do not call blocking I/O or system functions from the Lua standard library, including io.open, io.read, io.write, io.popen, and os.execute.

Nginx uses a single-threaded event-loop model, with one worker process handling many concurrent requests. When a nonblocking OpenResty API waits for the network, it suspends the current Lua coroutine so the worker can handle other requests. The standard Lua io.* functions and os.execute know nothing about the Nginx event loop. Calling one blocks the entire worker, forcing all other concurrent requests assigned to that process to wait as well.

The only exception is init_by_lua*, which runs at server startup before any client traffic arrives. Reading a few small local startup configuration files with io.open is fine there.

Once request processing begins, use OpenResty’s nonblocking alternatives:

  • Network communication with Redis, MySQL, HTTP, Kafka, and similar services: Use an official or community lua-resty-* library built on OpenResty cosockets, such as lua-resty-redis, lua-resty-mysql, or lua-resty-http.
  • External commands or subprocesses: Use the ngx.pipe module provided by lua-resty-core, or lua-resty-shell, which wraps it. These start subprocesses and communicate with them without blocking. Do not use io.popen or os.execute.

Later articles will explain the event-loop mechanics behind blocking operations. To see how much this rule can matter in production, read this troubleshooting case study: Lua io.popen Blocks Nginx’s Event Loop: A 150x Throughput Fix.

Summary: Syntax Is Only the Starting Point

Here is a short module that ties together local, tables, dot and colon calls, the res, err pattern, and ngx.null, so you can see what a real OpenResty Lua module looks like:

local redis = require "resty.redis"

local _M = {}

function _M.check_token(token)
    if not token or token == "" then
        return false, "missing token"
    end

    local red = redis:new()
    red:set_timeouts(1000, 1000, 1000) -- Connect, send, and read timeouts in ms

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.log(ngx.ERR, "failed to connect to redis: ", err)
        return false, err
    end

    local uid
    uid, err = red:get("token:" .. token)
    if not uid then
        -- Do not return a failed connection to the connection pool.
        ngx.log(ngx.ERR, "failed to get token from redis: ", err)
        return false, err
    end

    -- After a successful read, return the connection to the pool for reuse by later requests.
    ok, err = red:set_keepalive(10000, 100)
    if not ok then
        ngx.log(ngx.WARN, "failed to set keepalive: ", err)
    end

    if uid == ngx.null then
        return false, "invalid token"
    end

    return true, nil
end

return _M

If you can follow every line of this code, you already know enough Lua for OpenResty. Next, continue with How to Write Lua Modules in OpenResty: A Step-by-Step Example, where you will move code out of nginx.conf into reusable module files.

Once you are past this thin syntax barrier, the real work in writing good OpenResty applications lies in three areas:

  • Choosing the right execution phase: Understand the Nginx request lifecycle and which directive each piece of logic belongs in. The upcoming article Execution Phases: Where Should This *_by_lua Code Run? will cover this.
  • Reading and writing requests and responses with ngx.*: Learn to read headers, URL arguments, and request bodies, and to control response output and request flow. The upcoming articles Reading Requests and Writing Responses and Controlling Flow will cover these topics.
  • Using cosockets for nonblocking access to Redis and other services: Learn nonblocking network I/O and connection-pool practices. The upcoming article Cosockets: Why Blocking Libraries Stall Workers, and Your First Redis Connection will cover this.

These are the core topics the rest of this tutorial series will work through.

This article is part of the OpenResty tutorial series.

If you like this tutorial series, subscribe to this blog and our YouTube channel.

About the Author

Yichun Zhang (GitHub handle: agentzh) is the original creator of the OpenResty® open-source project and the CEO of OpenResty Inc..

Yichun is a pioneer of edge computing, dynamic tracing, and machine coding. He has more than 22 years of programming experience and 16 years of open-source experience, and has contributed more than a million lines of code to projects including the Linux kernel, Nginx, LuaJIT, GDB, SystemTap, LLVM, and Perl. He has also authored more than 60 open-source software libraries.