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

---
title: Lua Crash Course
description: Learn the essentials of Lua - variables, control flow, functions, tables, metatables, classes, and modules - in one page.
icon: graduation-cap
sidebar_position: 1
---

# Lua Crash Course

A fast, example-driven tour of Lua in the Neverlose CS2 runtime. Each section introduces small examples; where code continues an earlier example or demonstrates an error, the text calls that out.

<Note>
  CS2 uses LuaJIT 2.1 with Lua 5.2 compatibility enabled. Its sandbox exposes the [documented environment](/cs2/api_reference/lua/base), including `print` for output to the game console. Master the basics here, then explore the [API Reference](/cs2/api_reference/introduction/overview).
</Note>

## Comments

```lua
-- Two dashes start a one-line comment.

--[[
     Adding two ['s and ]'s makes it a
     multi-line comment.
--]]
```

## Variables and flow control

Numbers, strings, and booleans behave much like in Python. Variables are **global by default** - use `local` to scope them.

```lua
num = 42  -- Numbers can be integer or floating point.

s = 'walternate'           -- Immutable strings, single quotes.
t = "double-quotes are also fine"
u = [[ Double brackets
       start and end
       multi-line strings.]]
t = nil  -- Undefines t; Lua has garbage collection.
```

<Warning>
  Variables are **global by default**. Forgetting `local` is the most common source of bugs and name collisions in Lua scripts.

  ```lua
  thisIsGlobal = 5        -- Leaks into the global scope.
  local line = "hello"   -- Properly scoped to the block.
  ```
</Warning>

### Conditionals

```lua
local num, s, line = 42, "walternate", "reader"
if num > 40 then
  print('over 40')
elseif s ~= 'walternate' then  -- ~= is "not equals".
  print('not over 40')
else
  print('Winter is coming, ' .. line)  -- .. concatenates.
end
```

<Tip>
  Only `nil` and `false` are falsy - **`0` and `''` are truthy!** This trips up developers coming from C or JavaScript.

  ```lua
  local aBoolValue = false
  if not aBoolValue then print('it was false') end

  -- 'and' / 'or' short-circuit, mimicking a ? b : c:
  ans = aBoolValue and 'yes' or 'no'  --> 'no'
  ```
</Tip>

### Loops

<Tabs items={["while", "numeric-for", "repeat"]}>
  <Tab title="while">
    ```lua
    local num = 42
    while num < 50 do
      num = num + 1  -- No ++ or += operators.
    end
    ```
  </Tab>

  <Tab title="numeric-for">
    ```lua
    -- Range is begin, end[, step] and includes both ends.
    karlSum = 0
    for i = 1, 100 do
      karlSum = karlSum + i
    end

    -- Count down with a negative step:
    local fredSum = 0
    for j = 100, 1, -1 do fredSum = fredSum + j end
    ```
  </Tab>

  <Tab title="repeat">
    ```lua
    local num = 3
    repeat
      print('the way of the future')
      num = num - 1
    until num == 0
    ```
  </Tab>
</Tabs>

## Functions

Functions are first-class values - assign them, pass them around, and return them. Closures capture surrounding locals.

<Steps>
  <Step title="Define a function" icon="function-square">
    ```lua
    function fib(n)
      if n < 2 then return 1 end
      return fib(n - 2) + fib(n - 1)
    end
    ```
  </Step>

  <Step title="Return closures" icon="package">
    The returned function remembers `x` even after `adder` returns.

    ```lua
    function adder(x)
      return function (y) return x + y end
    end
    a1 = adder(9)
    print(a1(16))  --> 25
    ```
  </Step>

  <Step title="Work with multiple values" icon="list">
    Assignments and returns balance lists. Extra receivers become `nil`; extra senders are discarded.

    ```lua
    x, y, z = 1, 2, 3, 4  -- 4 is thrown away.

    function bar(a, b, c)
      print(a, b, c)
      return 4, 8, 15, 16, 23, 42
    end
    x, y = bar('zaphod')  --> prints "zaphod  nil  nil"
    ```
  </Step>
</Steps>

<Info>
  A call with a **single string or table argument** can drop the parentheses:

  ```lua
  local function h(options) print(options.key1) end
  print 'hello'              -- Same as print('hello').
  h{ key1 = 'Sonmi~451' }   -- Same as h({ key1 = ... }).
  ```
</Info>

## Tables

Tables are Lua's **only** compound data structure - associative arrays that work as both dictionaries and lists.

<Tabs>
  <Tab title="As dictionaries" icon="book-marked">
    ```lua
    -- String keys can use dot notation:
    t = { key1 = 'value1', key2 = false }
    print(t.key1)   -- 'value1'
    t.newKey = {}   -- Add a key/value pair.
    t.key2 = nil    -- Remove a key.

    -- Any non-nil value can be a key:
    u = { ['@!#'] = 'qbert', [6.28] = 'tau' }
    print(u[6.28])  -- 'tau'

    for key, val in pairs(u) do  -- Iterate every pair.
      print(key, val)
    end
    ```
  </Tab>

  <Tab title="As lists" icon="list-ordered">
    ```lua
    -- List literals implicitly set up integer keys:
    v = { 'value1', 'value2', 1.21, 'gigawatts' }

    for i = 1, #v do  -- #v is the length of the list.
      print(v[i])     -- Indices start at 1, not 0!
    end
    ```
  </Tab>
</Tabs>

<Warning>
  Lua indices **start at `1`**, and `#t` only gives a meaningful length for tables with consecutive integer keys. A "list" is not a real type - it's just a table used a certain way.
</Warning>

## Metatables and metamethods

A metatable gives a table operator-overloading and custom lookup behavior.

```lua
local f1 = { a = 1, b = 2 }
local f2 = { a = 1, b = 3 }
metafraction = {}
function metafraction.__add(f1, f2)
  local sum = {}
  sum.b = f1.b * f2.b
  sum.a = f1.a * f2.b + f2.a * f1.b
  return sum
end

setmetatable(f1, metafraction)
setmetatable(f2, metafraction)

s = f1 + f2  -- Calls __add(f1, f2) from f1's metatable.
```

The `__index` metamethod overloads failed lookups, enabling prototype-style defaults:

```lua
defaultFavs = { animal = 'gru', food = 'donuts' }
myFavs = { food = 'pizza' }
setmetatable(myFavs, { __index = defaultFavs })

eatenBy = myFavs.animal  -- 'gru' - found via the metatable.
```

<AccordionGroup>
  <Accordion title="Common metamethods reference" icon="table" description="The keys Lua recognizes on a metatable">
    | Metamethod            | Triggered by              |
    | --------------------- | ------------------------- |
    | `__add(a, b)`         | `a + b`                   |
    | `__sub(a, b)`         | `a - b`                   |
    | `__mul(a, b)`         | `a * b`                   |
    | `__div(a, b)`         | `a / b`                   |
    | `__mod(a, b)`         | `a % b`                   |
    | `__pow(a, b)`         | `a ^ b`                   |
    | `__unm(a)`            | `-a`                      |
    | `__concat(a, b)`      | `a .. b`                  |
    | `__len(a)`            | `#a`                      |
    | `__eq(a, b)`          | `a == b`                  |
    | `__lt(a, b)`          | `a < b`                   |
    | `__le(a, b)`          | `a <= b`                  |
    | `__index(a, b)`       | `a.b` (function or table) |
    | `__newindex(a, b, c)` | `a.b = c`                 |
    | `__call(a, ...)`      | `a(...)`                  |
  </Accordion>
</AccordionGroup>

## Classes and inheritance

Lua has no built-in classes - you build them from tables and metatables. The `:` syntax adds an implicit `self` argument.

```lua
Dog = {}

function Dog:new()
  local newObj = { sound = 'woof' }
  self.__index = self
  return setmetatable(newObj, self)
end

function Dog:makeSound()
  print('I say ' .. self.sound)
end

mrDog = Dog:new()
mrDog:makeSound()  -- 'I say woof'
```

<Info>
  `function Dog:new()` is shorthand for `function Dog.new(self)`. The colon just injects the first `self` argument - that's the whole trick behind Lua "methods".
</Info>

Continue the `Dog` example to build inheritance by chaining `__index` through another class:

```lua
LoudDog = Dog:new()  -- LoudDog inherits Dog's methods.

function LoudDog:makeSound()
  local s = self.sound .. ' '
  print(s .. s .. s)
end

seymour = LoudDog:new()
seymour:makeSound()  -- 'woof woof woof'
```

## Modules

Use `require` to load a module. It runs the file once, caches the return value, and keeps the file's locals private.

<Tabs items={["mod.lua", "main.lua"]}>
  <Tab title="mod.lua">
    ```lua
    local M = {}

    local function sayMyName()  -- Private to this file.
      print('Hrunkner')
    end

    function M.sayHello()       -- Exported.
      print('Why hello there')
      sayMyName()
    end

    return M
    ```
  </Tab>

  <Tab title="main.lua">
    ```lua
    local mod = require('mod')  -- Runs mod.lua once, then caches.

    mod.sayHello()   -- 'Why hello there' then 'Hrunkner'
    -- mod.sayMyName() would error: sayMyName is private to mod.lua.
    ```
  </Tab>
</Tabs>

<Tip>
  Use `require("lib/helper")` for `lib/helper.lua` inside the same extension. Paths are relative to the extension root, and modules are cached while the extension is loaded. Reload the extension to rerun its files. See [Requirements](/cs2/api_reference/extensions/requirements) for external dependencies and built-in modules.
</Tip>

## Further reading

<Columns cols={2}>
  <Card title="Advanced LuaJIT" icon="wand-sparkles" href="/cs2/api_reference/tutorials/advanced-luajit">
    Non-obvious LuaJIT 2.1 tricks once you know the basics.
  </Card>

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

  <Card title="API Reference" icon="code" href="/cs2/api_reference/introduction/overview">
    Explore the Neverlose Lua API: entity, render, trace, ui, utils, and more.
  </Card>
</Columns>
