Skip to content

Lua Style Guide

Matan Lurey edited this page Oct 3, 2021 · 9 revisions

The following is a style guide, enforced by code review, for this repository.

Do your best, we're not here to refuse contributions because lack of 100% compliance.

We will expect repeat contributors to understand our style.

Style

Spacing

Identifiers

Usage

Includes

Prefer require to #include

-- bad
#include !/some/file

-- good
require('!/some/file')

Before tts-expander v0.1.4, only #include was supported.

Using require means that standard Lua editors/formatters understand the syntax.

Variables

Avoid implicit global variables

If you are accessing (reading from or writing to) a global variable, use the _G prefix to make it explicit:

-- bad: it's not clear if "name" is global scope or not
if name then print(1) end

-- good: this is a local scoped variable
if someLocal then print(1) end

-- good: _G makes it clear this is a global scoped variable
if _G.name then print(1) end

Equality

Prefer tilde equals ~= to bang equals !=

-- bad
if someObj != nil then print(1) end

-- good
if someObj ~= nil then print(1) end

While some Lua engines, including TTS, support !=, ~= is more universally accepted.

Reference: http://www.lua.org/manual/5.2/manual.html#3.4.3

Prefer truthy-checks where possible

local someObj = getObjectFromGUID('1234abc')

-- bad
if someObj ~= nil then print(1) end

-- good
if someObj then print(1) end

If you want to test if an object exists, and it's possible to rely on truthy-ness, prefer it.

Caveat for if you have a variable that is non-nil but you explicitly want to only test for nil:

-- good
if minis ~= nil then
  if type(minis) == 'number' then
    -- process as number
  else
    -- process as array
  end
end

Design

TBD.

Clone this wiki locally