> Agent-readable docs index: /llms.txt. Download /docs.zip to grep all markdown files locally.

---
title: Advanced LuaJIT
description: Non-obvious LuaJIT 2.1 language tricks - syntax sugar, the and/or ternary, varargs, control flow, patterns, metamethods, and performance.
icon: wand-sparkles
sidebar_position: 3
---

# Advanced LuaJIT

A collection of LuaJIT 2.1 language features and idioms for the Neverlose CS2 runtime, from call syntax to tables and module patterns. If you're new to Lua, read the [Lua Crash Course](/cs2/api_reference/tutorials/lua-crash-course) first.

<Info>
  Targets **LuaJIT 2.1 with Lua 5.2 compatibility enabled**, including table `__len` and `rawlen`. The CS2 sandbox exposes the [documented libraries](/cs2/api_reference/extensions/globals-and-modules); an upstream LuaJIT library is not automatically available to extensions.
</Info>

## String literals: quotes and long brackets

`"double"` and `'single'` quotes are **completely identical** in Lua - same escapes, same type. Pick whichever lets you avoid escaping the quote *inside* the string:

```lua
local a = "it's fine"          -- ' needs no escaping inside "..."
local b = 'say "hi"'           -- " needs no escaping inside '...'
local c = "she said \"hi\""    -- escaping only when you mix
```

Combined with the **no-parentheses call sugar** (a call with a single string literal drops its parentheses), this is why you constantly see:

```lua
local ffi = require "ffi"      -- same as require("ffi")
local ffi = require 'ffi'      -- identical - quote style is your choice
require "bit"                  -- works for any single-string-argument call
```

<Note>
  The sugar applies to **one string (or one table) literal only**. `require "a", "b"` is a syntax error - anything with multiple arguments, or a variable instead of a literal, still needs parentheses: `require(name)`. The FFI examples require `"ffi"` in [extension.json](/cs2/api_reference/extensions/requirements).
</Note>

For multi-line strings or content full of quotes, use **long brackets** `[[ ... ]]`. They take no escapes at all, and `[==[ ... ]==]` (any number of `=`) lets you embed `]]`:

```lua
local sql = [[
  SELECT * FROM users
  WHERE name = "O'Brien"      -- both quote types, zero escaping
]]

local nested = [==[ contains a ]] sequence ]==]
```

<Tip>
  A long bracket that starts with an immediate newline drops that first newline - so `[[\nfoo]]` is just `"foo"`. Handy for keeping the opening `[[` on its own line without a leading blank.
</Tip>

## Syntax sugar worth abusing

<Steps>
  <Step title="String / table call without parentheses" icon="quote">
    `f "x"` is exactly `f("x")`, and `f {a=1}` is `f({a=1})`. Chain them to build a DSL:

    ```lua
    local function setting(name)
      return function(value) print(name, value) end
    end
    setting "enabled" (true) -- setting("enabled")(true)
    ```

    This works because `setting("enabled")` returns *another function*.
  </Step>

  <Step title="Methods on literals" icon="at-sign">
    Any string literal is a `string` object - call library methods directly (parentheses required around the literal):

    ```lua
    local hex = ("%02X"):format(255)   -- "FF"
    local pad = ("-"):rep(20)
    ```
  </Step>

  <Step title="Bare do...end blocks" icon="brackets">
    A standalone `do ... end` scopes locals and groups post-construction setup:

    ```lua
    local item = {} do
      item.color = "red"   -- configure, then let the temporaries die
    end
    ```
  </Step>

  <Step title="Multiple assignment & swap" icon="arrow-right-left">
    The right-hand side is fully evaluated before assignment, so swaps need no temp:

    ```lua
    local a, b = 10, 20
    a, b = b, a
    local point = {1, 2, 3}
    local x, y, z = unpack(point)
    ```
  </Step>
</Steps>

## The `and` / `or` ternary - and its trap

Lua's idiomatic ternary is `cond and a or b`. It's elegant until `a` itself is falsy:

<Tabs>
  <Tab title="The pitfall" icon="triangle-alert">
    ```lua
    local opts = { saveable = false }
    local flag = true
    -- Looks like a default of `true`, but it's broken:
    local saveable = opts.saveable or true
    -- If opts.saveable == false  ->  false or true  ->  true  (wrong!)

    -- Same bug with the ternary when the "true" branch is false:
    local x = flag and false or "fallback"   -- never yields false
    ```
  </Tab>

  <Tab title="The fix" icon="check">
    ```lua
    local opts = { saveable = false }
    -- Explicit nil check instead of `or`:
    local saveable = opts.saveable
    if saveable == nil then saveable = true end

    -- Strict boolean coercion:
    local value = true
    local b = (value == true) and true or false
    ```
  </Tab>
</Tabs>

## Truthiness and numbers

* **Only `nil` and `false` are falsy** - `0`, `""`, and `0/0` (NaN) are all truthy.
* **NaN is never equal to itself**: `0/0 ~= 0/0` is `true`. Use it to detect NaN: `local function isnan(x) return x ~= x end`.
* **`1/0` is `inf`**, `-1/0` is `-inf`, and `math.huge` is `inf`.
* **Hex float literals** exist: `0x1.8p1` is `3.0`, `0xFFp-4` is `15.9375` (`p` is the binary exponent).
* **`tonumber` takes a base** 2-36: `tonumber("ff", 16)` -> `255`, `tonumber("777", 8)` -> `511`.

```lua
-- # on a table with holes returns SOME border, not "the length":
print(#({1, 2, nil, 4}))   -- may be 2 OR 4 - undefined
-- Reliable emptiness check, regardless of key types:
local t = {}
if next(t) == nil then --[[ empty ]] end
```

<Warning>
  **`t[1]` and `t[1.0]` are the same key**. Use a string such as `"1"` when you need a distinct key.
</Warning>

## Control flow

### `goto` and `::continue::`

LuaJIT 2.1 (and Lua 5.2+) has `goto`. The canonical use is a `continue`:

```lua
local items = {{enabled = true}, {enabled = false}, {enabled = true}}
for i = 1, #items do
  local it = items[i]
  if not it.enabled then goto continue end
  print("Enabled item", i)
  ::continue::
end
```

<Note>
  `goto` can only jump to a label in the same or an enclosing block, and cannot jump *into* a local's scope. Beyond `continue`, it's handy for compact state machines without a dispatch table.
</Note>

### `repeat ... until true` - continue without goto

Before `goto` existed, the idiom for `continue` was a one-shot `repeat` loop where `break` jumps to the end. It still works (even on stock Lua 5.1) and is common in older code:

```lua
for i = 1, 5 do repeat
  if i % 2 == 0 then break end     -- `break` here behaves like `continue`
  print(i)                        -- 1, 3, 5
until true end                     -- the outer loop is what actually iterates
```

### Proper tail calls

`return f(x)` is a **tail call** - Lua reuses the stack frame, so deep/mutual recursion never overflows:

```lua
local function loop(i, acc)
  if i == 0 then return acc end
  return loop(i - 1, acc + i)   -- no stack growth, even for millions of iterations
end
```

## Varargs and multiple returns

<Tabs items={["Count, don't trust #", "Pack a multireturn", "Forward only the rest"]}>
  <Tab title="Count, don't trust #">
    ```lua
    -- # is unreliable with holes; select('#', ...) counts trailing nils too.
    local function f(...)
      local n = select('#', ...)   -- true argument count
      for i = 1, n do
        local v = select(i, ...)   -- nth value (and everything after)
        print(i, v)
      end
    end
    ```
  </Tab>

  <Tab title="Pack a multireturn">
    ```lua
    -- {f()} captures every return value into an array.
    local function dimensions() return 320, 180 end
    local args = { dimensions() }
    -- Decide scalar vs list by how many came back:
    local value = #args > 1 and args or args[1]
    ```
  </Tab>

  <Tab title="Forward only the rest">
    ```lua
    -- select(n, ...) returns the nth arg AND all following ones.
    local function tail(_, ...) return ... end
    print(tail(1, 2, 3, 4))   -- 2  3  4
    ```
  </Tab>
</Tabs>

<Warning>
  `{...}` silently drops trailing `nil`s from the length operator. If `nil` is a meaningful value, store the count explicitly: `local t = { n = select('#', ...), ... }` and iterate `1, t.n`.
</Warning>

### Expression adjustment rules

A call expands to all its return values **only when it's the last item** in a list; anywhere else it's truncated to one. Wrapping it in parentheses forces a single value:

```lua
local function f() return 1, 2 end
local function g() return 3, 4 end
local function h() return 5, 6 end
print(f(), 10)       -- f() truncated to 1 value
print(10, f())       -- f() expanded to all values
local t = { g(), h() }   -- g() -> 1 value, h() -> all of them
local x = (f())          -- parentheses FORCE exactly one value
```

<Tip>
  `assert` returns its arguments on success, so it chains around calls that signal failure with `nil, err`:

  ```lua
  local text = "320"
  local width = assert(tonumber(text), "width must be numeric")
  print(width) -- 320; invalid numeric text would raise the supplied error.
  ```
</Tip>

## Strings and patterns

Lua patterns are not regex, but they have a few power features people miss:

<AccordionGroup>
  <Accordion title="Byte escapes and multi-return string.byte" icon="binary">
    ```lua
    local space   = "\x20"            -- hex escape
    local hair    = "\xE2\x80\x8A"    -- raw UTF-8 bytes (U+200A HAIR SPACE)

    -- string.byte returns a range of bytes at once:
    local r, g, b = ("\xFF\x80\x00"):byte(1, 3)   -- 255  128  0
    ```
  </Accordion>

  <Accordion title="Captures with gmatch / gsub" icon="regex">
    ```lua
    -- Parse "key:value;" pairs:
    for k, v in ("a:1;b:2;"):gmatch("([^:]+):([^;]+);") do
      print(k, v)   -- a 1 / b 2
    end

    -- gsub with a table replacement (looked up per match):
    local out = ("hi {name}"):gsub("{(%w+)}", { name = "world" })
    print(out)   -- hi world   (table lookup also works as the replacement)
    ```
  </Accordion>

  <Accordion title="%b and %f - balanced match and frontier" icon="braces">
    ```lua
    -- %bxy matches a balanced pair, e.g. %b() for nested parentheses:
    print(("f(a, g(b))"):match("%b()"))   -- (a, g(b))

    -- %f[set] is a frontier: a zero-width boundary into `set`.
    -- Match whole words starting with an uppercase letter:
    for w in ("Hello big World"):gmatch("%f[%a]%u%a*") do print(w) end  -- Hello / World
    ```
  </Accordion>
</AccordionGroup>

## The `bit` library

LuaJIT's `bit` library does fast 32-bit integer math (results are signed 32-bit).

```lua
-- FNV-1a hash, with the FNV prime multiply decomposed into shifts:
local function fnv1a(str)
  local h = 0x811c9dc5
  for i = 1, #str do
    h = bit.bxor(h, str:byte(i))
    h = h + bit.lshift(h,1) + bit.lshift(h,4)
          + bit.lshift(h,7) + bit.lshift(h,8) + bit.lshift(h,24)  -- = 0x01000193
  end
  return h % 0x100000000   -- wrap to unsigned 32-bit
end
```

<Tip>
  Beyond the basics, the `bit` library also gives you `bit.tohex`, `bit.tobit` (normalize to int32), `bit.ror` / `bit.rol` (rotates), and `bit.bswap` (byte-swap, e.g. endianness flips). These are JIT-friendly and far faster than arithmetic equivalents.
</Tip>

## Standard library extras

These standard-library features are available in the CS2 runtime:

```lua
print(string.rep("ab", 3, "-")) -- "ab-ab-ab" (separator)
local t = {"one", "two", "three"}
print(table.concat(t, ", ", 2, 3)) -- "two, three" (slice)

local function add(a, b) return a + b end
local ok, total = xpcall(add, tostring, 2, 3) -- Forwards arguments to add.
print(ok, total) -- true, 5

local function last(...) return select(-1, ...) end
print(last("one", "two", "three")) -- "three"
```

## Building strings and serializing values

Collect text fragments in a table, then join them once with `table.concat`. For binary serialization, the host-provided [`msgpack`](/cs2/api_reference/data/msgpack) library round-trips Lua values:

```lua
local parts = {"hp=", tostring(100), "\n"}
local text = table.concat(parts) -- "hp=100\n"

local blob = msgpack.pack({1, 2, name = "x"})
local obj = msgpack.unpack(blob)
print(obj.name) -- "x"
```

<Note>
  The current Neverlose runtime does not expose `string.buffer`. Use [`json`](/cs2/api_reference/data/json) when the serialized data needs to be human-readable.
</Note>

## Scoping and module patterns

<Steps>
  <Step title="IIFE module with private state" icon="box">
    Wrap a unit in an immediately-invoked function and expose only what you assign outward:

    ```lua
    local M do (function()
      local secret = 42          -- private
      M = { get = function() return secret end }
    end)() end
    ```
  </Step>

  <Step title="Forward-declare for mutual recursion" icon="arrow-left-right">
    Declare locals up front so two functions can reference each other:

    ```lua
    local even, odd
    function even(n) return n == 0 or odd(n - 1) end
    function odd(n)  return n ~= 0 and even(n - 1) end
    ```
  </Step>

  <Step title="Upvalue captured before assignment" icon="link">
    A closure can reference a local that's assigned *later* - by call time it's set:

    ```lua
    local self
    local mt = { describe = function() return self.name end }
    self = setmetatable({ name = "obj" }, { __index = mt })
    ```
  </Step>

  <Step title="local function for self-recursion" icon="repeat">
    `local function f` declares the name *before* the body, so `f` can call itself.
    `local f = function() f() end` would capture a **global** `f`, not the local.
  </Step>

  <Step title="Each loop iteration gets a fresh local" icon="repeat-2">
    Unlike old JavaScript `var`, every iteration of a `for` loop binds a **new** variable, so closures capture distinct values:

    ```lua
    local fns = {}
    for i = 1, 3 do fns[i] = function() return i end end
    print(fns[1](), fns[2](), fns[3]())   -- 1  2  3   (not 3 3 3)
    ```
  </Step>
</Steps>

## Metamethods beyond OOP

Metamethods aren't just for classes. Any operator can be repurposed.

<Tabs>
  <Tab title="Operator overloading" icon="plus">
    Overload an arithmetic operator to mean something else entirely. A library can use `^` (`__pow`) as a hidden "unlock" call:

    ```lua
    local lib = setmetatable({ SIGNED = 0x1337 }, {
      __pow = function(self, token)
        assert(token == self.SIGNED, "bad token")
        return self        -- hand back the "real" library
      end,
    })

    lib = lib ^ lib.SIGNED   -- looks like math, is actually a handshake
    ```
  </Tab>

  <Tab title="__index as a function" icon="function-square">
    `__index` can be a **function**, turning every missing-key access into a computed lookup (virtual dispatch):

    ```lua
    local proxy = setmetatable({}, {
      __index = function(t, key)
        return function(...) print("called", key, ...) end
      end,
    })

    proxy.anything("x")   -- prints: called  anything  x
    ```
  </Tab>

  <Tab title="__call" icon="phone">
    `__call` makes a table behave like a function - useful for callable config objects:

    ```lua
    local counter = setmetatable({ n = 0 }, {
      __call = function(self) self.n = self.n + 1; return self.n end,
    })

    print(counter(), counter())   -- 1  2
    ```
  </Tab>
</Tabs>

<Tip>
  Use `rawget` / `rawset` / `rawequal` / `rawlen` to bypass metamethods when you need the *real* table state - essential inside an `__index`/`__newindex` to avoid infinite recursion.
</Tip>

### Weak tables (`__mode`)

A table with `__mode` lets the GC collect its entries. Great for caches keyed by objects without leaking them:

```lua
local cache = setmetatable({}, { __mode = "k" })  -- "k", "v", or "kv"
local object = {}
cache[object] = "computed result"
object = nil -- The key can now be collected, removing its cache entry.
```

### Locking and read-only tables

`__metatable` hides the real metatable, and an erroring `__newindex` makes a table tamper-proof - a common way to ship a "protected" module:

```lua
local real_impl = { version = 1 }
local api = setmetatable({}, {
  __metatable = false,   -- getmetatable() returns false; setmetatable() errors
  __index     = real_impl,
  __newindex  = function(_, k) error("read-only: " .. tostring(k), 2) end,
})
```

<Note>
  The `2` passed to `error` blames the **caller's** line, not the line inside `__newindex` - so the error points at the offending write.
</Note>

## Performance notes (LuaJIT-specific)

<Columns cols={2}>
  <Card title="Preallocate tables" icon="database">
    `require("table.new")(narr, nhash)` allocates a table with capacity up front; `require("table.clear")(t)` empties one for reuse without churning the GC.
  </Card>

  <Card title="Cache globals to locals" icon="gauge">
    Hoist hot globals/fields into locals (`local sin = math.sin`) - local access is a register, global access is a hash lookup.
  </Card>

  <Card title="Build strings with concat" icon="layers">
    `table.concat(parts)` beats repeated `..` in loops - it avoids creating an intermediate string per concatenation.
  </Card>

  <Card title="Know what is NYI" icon="triangle-alert">
    Some operations abort trace compilation and fall back to the interpreter. Keep hot loops free of NYI calls so the compiler can stay on-trace.
  </Card>
</Columns>

## Further reading

<Columns cols={2}>
  <Card title="Lua Crash Course" icon="graduation-cap" href="/cs2/api_reference/tutorials/lua-crash-course">
    The language fundamentals, if you want a refresher first.
  </Card>

  <Card title="FFI Crash Course" icon="cpu" href="/cs2/api_reference/tutorials/ffi-crash-course">
    Reach into memory and call native functions from Lua.
  </Card>

  <Card title="Lua 5.1 Reference" icon="book-open" href="https://www.lua.org/manual/5.1/" arrow>
    The base language manual LuaJIT implements.
  </Card>

  <Card title="LuaJIT Extensions" icon="external-link" href="https://luajit.org/extensions.html" arrow>
    `bit`, `table.new`/`table.clear`, and the 5.2 features LuaJIT backports.
  </Card>
</Columns>
