One-liners

Contents

One-liners#

Single-expression Lua idioms.

Ternary via short-circuit and / or (consequent must be truthy).

local label = (n % 2 == 0) and "even" or "odd"

Length of a sequence (integer-keyed table starting at 1).

#xs

Concatenate strings with ..; reach for table.concat for many parts.

table.concat(parts, ",")

Split a string with gmatch and a non-separator pattern.

for word in string.gmatch(s, "%S+") do print(word) end

Pattern match.

local user, host = s:match("^(%w+)@([%w.-]+)$")

Read a whole file.

local text = io.open("notes.txt", "r"):read("*a")

Sort a sequence in place.

table.sort(xs)

Sort with a comparator.

table.sort(xs, function(a, b) return a.score > b.score end)

Default value via or.

local port = cfg.port or 8080

Round-trip JSON via cjson (if available).

local cjson = require("cjson"); local obj = cjson.decode(text)

References#

  • Snippets for the snippets catalogue.

  • Types for the underlying types.