simple but effective Lua type system using metatables
Metatype is a library and specification for creating performant, documented, and
typo-safe Lua record-types which can be formatted.
Turn off typo checking by setting the global LUA_OPT=3 or higher.
local G = G or _G
--- module documentation
local M = G.mod and mod'myMod' or {} -- (see pkg)
local mty = require'metaty'
-- Documentation for Pos (position)
M.Pos = mty'Pos' {
'x[int]: x coordinate',
'y[int]: y coordinate', y = 0,
}
local p1 = Pos{x=4}
local p1 = Pos{x=4, y=3, z=5} -- error if checking turned on
The above expands to the following. Note that the "typosafe" elements
are removed when
LUA_OPT > 3
local M = {}
local metaty = require'metaty'
local Pos = setmetatable({
__name='Pos',
y = 0,
-- used with metaty.Fmt and help()
__fields={'x', 'y', x='[int]', y='[int]'},
__newindex = metaty.newindex, -- typosafe setting
}, {
__call = function(T, t)
metaty.fieldsCheck(T.__fields, t) -- typosafe constructor
return setmetatable(t, T)
end,
__index = metaty.index, -- typosafe getting
})
Pos.__index = Pos
-- `mod` gives documentation reflection
PKG_LOCS[M.myFn] = 'path/to/file.lua:123'
PKG_NAMES[M.myFn] = 'mymod.Pos'
PKG_LOOKUP['myMod.Pos'] = M.Pos
- ty(v) return the metaty of v. For tables this is getmetatable(v),
else it is type(v).
- metaty'name' {'field1[type] documentation', 'field2[type]'}
creates a documented and typo-safe record type (see examples) field can also be in the form {type} for a list
of the type or {string: type} for a map of the type.
- @<decimal> (i.e. @2) can be put after the type to specify the
decimal value to use for the field when de/serializing.
It is recommended that once you assign a field to a decimal value to
never change it if there is any chance it is stored or being used
by an RPC service/etc with the previous version.