Coming from Lua

Midnight keeps Lua's semantics: the same values, tables, metatables, closures, coroutines, and standard library. Everything you know carries straight over, and everything you write still becomes plain Lua. This page has two halves:

What you get

In Lua you writeIn Midnight
x = x or default (and hope x is never false)parameter defaults
local ok, err = pcall(function() ... end)catch
a and b or c (and hope b is never falsy)if as a value
if t == 'a' then ... elseif t == 'b' then ...match
setmetatable({}, Lamp), Lamp.__index = Lampclass
local M = {} ... return Mmodule
local MAX = 3 -- please don't change thisconst
local floor, max = math.floor, math.maxdestructuring
'a ' .. tostring(b) .. ' c'interpolation

Defaults that respect false

x = x or default replaces false along with nil, so a boolean option that defaults to true needs the long form. Midnight's defaults only fill in nil, and destructured options get them too:

-- Lua
local function connect(host, opts)
  host = host or 'localhost'
  opts = opts or {}
  local retries = opts.retries or 3
  local verbose = opts.verbose
  if verbose == nil then verbose = true end
  -- ...
end
midnight
local function connect(host = 'localhost', opts = {}) {
  local { retries = 3, verbose = true } = opts
  print("{host}: {retries} retries, verbose {verbose}")
}

connect()                          -- localhost: 3 retries, verbose true
connect('db', { verbose = false }) -- db: 3 retries, verbose false

Getting protected calls without overloaded returns

pcall wants a function, returns a flag you have to check, and hands back the error in the same variable as the result. catch takes the expression as is, and gives you the value or the handler's:

-- Lua
local ok, cfg = pcall(load_config, path)
if not ok then cfg = DEFAULTS end

local ok, data = pcall(json.decode, body)
if not ok then return nil, 'bad json: ' .. tostring(data) end
-- Midnight
local cfg = load_config(path) catch DEFAULTS
local data = json.decode(body) catch e { return nil, "bad json: {e}" }

The handler's return returns from the enclosing function, like the Lua version. There's no way to drop an error by accident. To ignore one: catch nil. See catch.

A ternary that works

a and b or c is Lua's ternary, until b is false or nil and you get c instead. if is an expression in Midnight:

-- Lua: if user.flag is false, this is true
local enabled = user.is_admin and user.flag or true
local enabled = if user.is_admin { user.flag } else { true }

midnight lint also points out the and / or cases that can go wrong.

match instead of if chains

-- Lua
local kind = type(v)
if kind == 'string' then return 'a string of ' .. #v
elseif kind == 'number' or kind == 'boolean' then return tostring(v)
else return 'something else' end
midnight
local function describe(v) {
  return match type(v) {
    'string' => { "a string of {#v}" }
    'number' | 'boolean' => { tostring(v) }
    _ => { 'something else' }
  }
}

print(describe('owl'), describe(3), describe({}))

The subject is evaluated once, exactly one arm runs, and an arm can add a guard (_ if snoring =>). See match.

Classes without the boilerplate

-- Lua
local Lamp = {}
Lamp.__index = Lamp

function Lamp.new(room)
  local self = setmetatable({}, Lamp)
  self.room = room
  return self
end

function Lamp:off() return self.room .. ' is dark' end
midnight
local class Lamp {
  new(room) { self.room = room }
  off() { return "{self.room} is dark" }
}

print(Lamp.new('hall'):off()) -- hall is dark

It's the same metatable underneath, so Lua code can use Midnight classes and the other way around. Inheritance, super, and metamethods are in Classes.

Modules without the M table

-- Lua
local M = {}
local function helper() return 'zz' end
function M.snore() return helper() end
return M
local function helper() { return 'zz' }
module function snore() { return helper() }

Exports are visible in the whole file, so they can call each other in any order. See module.

Constants that stay constant

A capitalized name is a promise nobody checks, and Lua 5.4's <const> still lets you change the table. Midnight's const is checked when compiling, and a table written in it is frozen:

const site = 'https://example.com'
const limits = { retries = 3, timeout = 30 }

site = 'x'          -- compile error: cannot assign to const 'site'
limits.retries = 5  -- runtime error: attempt to modify a read-only table

See const.

Destructuring

-- Lua
local floor, max = math.floor, math.max
local name, age = person.name, person.age or 0
local { floor, max } = math
local { name, age = 0 } = person
local [first, second] = list

Strings without the dots

-- Lua
print('slept ' .. tostring(hours) .. ' hours (' .. string.format('%.1f', pct) .. '%)')
midnight
local hours, pct = 7, 93.333
print("slept {hours} hours ({pct:%.1f}%)") -- slept 7 hours (93.3%)

Single quoted strings don't interpolate, so '{literal}' stays as written.

What trips you up

Midnight is close enough to Lua that the differences hide. These are the ones that bite.

The syntax at a glance

LuaMidnight
if x then ... endif x { ... }
while x do ... endwhile x { ... }
repeat ... until xrepeat { ... } until x
function(a) return a end(a) -> a
a ~= ba != b
a and b or ca && b || c, or if a { b } else { c }
not a!a
x = x + 1x += 1
print 'hi'print('hi')
('%d'):format(n)'%d':format(n)
'a' .. tostring(b)"a{b}"
local M = {} ... return Mmodule function f() { ... }
local x = opts.x or 1local { x = 1 } = opts

Not equal is !=

This is the one you'll type wrong the most. Every operator in Midnight has an op= form, and ~ is xor, so ~= already means "xor this into that":

midnight
local flags = 0xff
flags ~= 0x0f
print(flags)  -- 240

Writing ~= where a comparison belongs fails to compile, with a hint:

unexpected token '~=', did you mean '!='?

Symbols instead of and, or, not

&&, ||, and ! replace and, or, and not, with the same meaning (they short circuit and return an operand). The old words aren't keywords anymore, they're ordinary names, so if not done { is a syntax error, not a negation.

The a && b || c idiom has Lua's old trap: if b is nil or false, you get c. An if expression doesn't, and midnight lint points out the risky cases.

Calls need parentheses

Lua lets you drop the parentheses when the only argument is a string or a table. Midnight doesn't:

-- Lua
require 'foo'
setup { verbose = true }
-- Midnight
require('foo')
setup({ verbose = true })

Anonymous functions are arrows

function(...) ... end isn't valid as an expression. Use an arrow, and => for methods that need self (see Arrow functions):

table.sort(owls, (a, b) -> a.age < b.age)

Named declarations (local function f() { }, function obj:m() { }) are still written with function.

Newlines settle ambiguous calls

Lua reads a ( at the start of a line as a call on whatever came before it, which bites when you start a line with a parenthesized expression:

local lamp = get_lamp
(lamp_fallback or noop)()   -- Lua: get_lamp(lamp_fallback or noop)()

Midnight treats the line break as the end of the statement, so those are two statements, which is almost always what was meant. To chain the call, keep it on one line. ; still works if you want to be explicit.

No semicolons in tables

Lua allows ; between table fields ({ x = 1; 'a' }). Midnight only allows commas, plus an optional trailing one.

Some Lua keywords are just names

and, or, not, then, and end aren't keywords, so they can be variable or field names. When compiled to Lua they're renamed (end becomes end_) and globals become _G["then"], so the output stays valid.

On the other side, Midnight reserves continue, global, and module. Since module is a keyword, Lua 5.1's module() function can't be called (it's been discouraged since Lua 5.2 anyway).

The runtime is Lua 5.1 (plus goto)

Midnight runs on gopher-lua, which implements Lua 5.1. Code written for newer Luas mostly works, with a few gaps to know about:

Running compiled Lua elsewhere

midnight compile and midnight -c produce Lua for other runtimes. The output is valid Lua 5.1 and LuaJIT, except:

Statements stay on their original lines, so errors in the compiled Lua still report Midnight line numbers. Comments aren't kept.

Coming from Erde

Midnight accepts the language of the Erde reference compiler, and is tested against its spec suite. On top of that it adds match, if and match expressions, catch, const, classes, interpolation formats, and markup. The other differences: