# How to format Lua code

> A Lua style guide for MoonLoader scripts and open-source projects: quotes, snake_case, indentation, comments, tables, function calls, DRY. Based on the LuaRocks guide.

- URL: https://pakulichev.com/en/wiki/lua-code-style
- Author: Pakulichev (https://pakulichev.com/)
- Language: en
- Updated: 2026-10-15
- Whole site for LLMs: https://pakulichev.com/llms.txt (index), https://pakulichev.com/llms-full.txt (full text)

In January 2021 I posted a guide on formatting Lua code on BLAST.HK. It's based on open sources, mainly the style guide by Hisham Muhammad, one of the authors of LuaRocks. These are recommendations. They're especially useful when other people read your code, in open source and in a team. Below is a short digest with examples.

## Strings

Put strings in double quotes. Keep single quotes for characters and for strings that contain double quotes:

```lua
local name = "Pavel_Garson"
local sep = ','
local msg = 'He said: "hello"'
```

## Names

Functions and variables go in `snake_case`. Start functions that check something with `is_`. Above a function, briefly describe its arguments and what it returns:

```lua
-- ped: character handle; returns true if it is in a vehicle
local function is_in_vehicle(ped)
  return isCharInAnyCar(ped)
end
```

## Indentation and lines

- Indent with 2–3 spaces, the same throughout the file.
- One statement per line.
- Wrap long lines and conditions.
- Don't align `=` with tabs across neighboring lines: the alignment breaks with the very first edit.

## Comments

Put one space after `--`. Start a multi-line comment on a new line and indent it:

```lua
--[[
  Player synchronization.
  Called every 100 ms.
]]
```

## Tables

Write keys as they are; use square brackets only when the key is stored in a variable:

```lua
local cfg = { nick = "Pavel_Garson", rank = 5 }
cfg[field] = value
```

## Calls

Always use parentheses, even with a single argument: `require("socket")`, not `require "socket"`. For short conditions, the and/or "ternary" works:

```lua
local label = is_online and "online" or "offline"
```

It breaks if the middle value can be `false` or `nil`; in that case write a regular `if`.

## Repetition

Move repeated code into a function. But a function made for a single call is just as unnecessary: all it does is make the reader jump around the file.

## FAQ

### What naming style is used in Lua?

snake_case for functions and variables. Functions that check something are handy to prefix with is_, for example is_player_alive.

### Which quotes should I use for strings in Lua?

Double quotes by default. Single quotes for single characters and for strings that contain double quotes.

### Should I use parentheses when calling a Lua function with one argument?

Yes, always: require("socket"), not require "socket". That way the call is obvious at a glance.
