Get documentation on any Lua object. Includes documentation for several items
in the lua stdlibrary.
Note: This requires the PKG protocol to be installed, see
lib/pkg
Making a library's types self-documenting is easy:
local G = G or _G
-- My module docs
local M = G.mod and mod'myModName' or {}
--- my fn docs in [$cxt]
M.myFn = function(a, b) --> string
-- do stuff
end
See Package_pkg and Package_cxt for more details.
Other Resources
Builds on metaty to add the ability to extract and format documentation.
Also offers the Cmd and Cmds types for documenting shell commands.
Types: Doc Main
Functions
- fn tryfind(obj) -> any?
Find the object/name or return nil.
- fn find(obj) -> any
Find the object/name.
Object passed to __doc methods.
Aids in writing cxt.
Fields:
Methods
- fn:level(add) -> int: current level
Add to the indent level and get the new value
call with add=nil to just get the current level
- fn:write(...)
Same as file:write.
- fn:flush()
- fn:close()
- fn:bold('[*%s]', text)
- fn:code(code)
- fn:link(link, text)
- fn:hdrlevel(add) -> int
- fn:named(name, id)
- (content, name)
- (loc) -> (commentLines, codeLines)
- fn:fnsig(code) -> (string, isMethod)
Extract the function signature from the lines of code.
- fn:declfn(fn, name, id) -> (cmt, sig, isMethod)
Declare the function definition
- fn:mod(m)
Document the module.
Get cxt documentation for symbol.
Fields:
- .towhere to write output.
Functions
- fn keyword() -> setmetatable({}, Keyword)
- fn next(tbl, key) -> nextKey
Get the next key in the table. Used for iterating through tables.
If key=nil returns the first key. Returns nil when key is
the last key.
- fn pcall(fn, ...) -> ok, fn(...)
call a function but catch errors. Returns ok followed by the function
results. If not ok, returns the error.
- fn select
select elements in varargs ... at and after index.
Special value: if index='#' then returns length of ...
- fn type(val) -> string
Get the type of val. Possible return values are:
- data: nil number string boolean table
- other: function thread userdata
See also: metaty.ty(v) for metatypes
- fn setmetatable
Sets the metatable on the table which can get gotten with
getmetatable and affects the behavior of operators.
All metamethods: __index (i.e. t[k]) NOTE: these are only called
__newindex (i.e. t[k] = v) when key is missing!
__call (i.e. t())
__tostring (i.e. tostring(t))
+ - * / // %
__add __sub __mul __div __idiv __mod
__unm
& | ~ << >> ^
__band __bor __bnot __shl __shr __pow
== < <= # ..
__eq __lt __le __len __concat
__name
See also metaty metamethods: __fields __fmt
- fn getmetatable(t) -> mt
See setmetatable.
- fn tostring(v) -> string
Convert any value to a string by calling __tostring or using lua's default.
- fn string.concat(sep, ...) -> string
concatenate the string arguments.
- fn string.find(subj, pat, index=1) -> (si, ei, ...matches)
Find the pattern in the subj (subject) string, starting at the index.
returns the si (start index), ei (end index) and match groups
(see #string.match).
T.eq({2, 4}, {find('%w+', ' bob is nice')})
T.eq({2, 7, 'is'}, {find(' bob is nice', '%w+ (%w+)')})
Character classes for matching specific sets: . all characters
%a letters
%c control characters
%d digits
%l lower case letters
%p punctuation characters
%s space characters
%u upper case letters
%w alphanumeric characters
%x hexadecimal digits
%z the character with representation 0
Magic characters, . indicates one character, more indicates many
%. selects a character class or escapes a magic char
(...) create a group
[...] create your own character class
[^..] inversion of [...]
+. match one or more of previous class (NOT group)
*. match zero or more of previous class (NOT group)
? match zero or one of previous class (NOT group)
^... if at pat[1], match only beggining of text
...$ if at pat[#pat], match only end of text
%1-9 matches the previously matched group index EXACTLY
- fn string.match(subj, pat, index=1) -> ...groups
Return the capture groups of pat or the whole match if no capture groups.
index: where to start the search and can be negative.
See also: string.find.
- fn string.gmatch(subj, pat, index=1) -> iterator()
Return an iterator function that when called returns the next capture group.
index: where to start the search and can be negative.
See also: string.find.
- fn string.sub(subj, si, ei) -> str[si:ei]
Return substring by index. ("1234"):sub(3,4) == "34"
Note: This is confusingly named considering string.gsub uses pattern
matching. Such is life.
- fn string.gsub(subj, pat, repl, index=1) -> string
Substittue all matches of pattern with repl, returning the new string.
repl can be a:
- string: replace with the string except %1-9 will be
a matched group from pat and %% is a literal %.
- table: the table will be queried for every match using
the first capture as key.
- function(...matches) -> string: the function will be called
with all match groups for each match.
See also: string.find for pattern documentation.
- fn string.format(fmt: str, ...) -> str
Format values into a fmt string, i.e: format('%s: %i', 'age', 42)
Directives:
| %% |
literal % char |
| %d |
decimal |
| %o |
octal |
| %x |
hexidecimal (%X uppercase) |
| %f |
floating point |
| %s |
string |
Directive control structure (ignore spaces): % (specifier width)? directive
Where width is an integer and specifier can be one of
| + |
right justify to width (the default) |
| - |
left justify to width |
| |
prefix a positive number with a space |
| # |
prefix o, x or X directives with 0, 0x and 0X respectively |
| 0 |
left-pad a number with zeros |
Examples: sfmt = string.format
T.eq('age: 42', sfmt('%s: %i', 'age', 42))
T.eq('age: 42', sfmt('%s: %5i', 'age', 42))
T.eq('age: 42 ', sfmt('%s: %-5i', 'age', 42))
T.eq('age: 00042', sfmt('%s: %05i', 'age', 42)
- fn string.byte(str, si=1, ei=si) -> ...ints
Get ASCII (integer) codes for s[si:ei
Example:
T.eq({98, 99}, {string.byte('abcd', 2, 3)})
*
fn string.char(c1, c2, ...) -> string
convert character codes to string and concatenate
*
fn string.rep
repeat str n times with separator
*
fn string.pack
pack the values as bytes into the string using the strtys.
strtys is a string of the form:
| < > = |
(start only) little / big / native endian |
| !# |
(start only) max alignment = # bytes |
| b B |
signed / unsigned byte |
| h H l L |
native short(h) and long(l) + unsigned vers |
| i# I# |
signed/unsigned int with # bytes |
| f d |
native float / double |
| T |
size_t |
| c# |
fixed-sized string of # bytes (unaligned) |
| z |
zero-terminated string (unaligned) |
| s# |
counted string of size # bytes |
| x |
one byte of padding |
| Xo |
align to option o, i.e. Xi4 |
| j J n |
lua Integer / Unsigned / Number |
Example:
T.eq(string.pack('>i2i2', 0x1234, 0x5678) == '\x12\x34\x56\x78')]
*
fn string.unpack
See string.pack for the fmt
*
fn string.packsize
Get the size which is used by strtys.
*
fn string.lower
not documented: see
string module
*
fn string.upper
not documented: see
string module
*
fn string.len
not documented: see
string module
*
fn string.dump
not documented: see
string module
*
fn string.reverse
not documented: see
string module
*
fn table.update(to, from) -> to
update to with from, return to.
Note: this is an addon from metaty.
*
fn table.concat(t, sep='') -> string
concatenate a table of strings with optional separator.
Examples:
concat = table.concat
T.eq(1..' = '..3, concat{1, ' = ', 3})
T.eq('1, 2, 3', concat({1, 2, 3}, ', ')
*
fn table.remove(t, index=#table) -> t[index]
remove an item from a table, returning it.
The table is shifted if index < #table which may cost up to O(n)
*
fn table.sort(list, cmp=lt) -> nil
sort a table in place using a comparison function
cmp who's behavior
must be:
cmp(a, b) --> makeAFirst
*
fn table.insert
insert or push to table (list-like)
Example:
local push = table.insert
local t = {}
-- push/append behavior
push(t, 'd') -- {'d'
push(t, 'e') -- {'d', 'e'}
-- insert behavior
table.insert(t, 'b', 1) -- {'b', 'd', 'e'}
table.insert(t, 'c', 2) -- {'b', 'c', 'd', 'e'}
T.eq({'b', 'c', 'd', 'e'}, t)
*
fn table.move
Move values from one list to another.
Note that
si=startIndex and
ei=endIndex (inclusive).
Equivalent to the following, though done in a way
that will properly handle overlapping data:
ti = siTo
for fi=siFrom,eiFrom do
to[ti] = from[fi]; ti = ti + 1
end
*
fn io.popen
Execute shell command in separate process.
See also:
- os.execute(): docs on file:close()
- lib/civix.sh(): ergonomic blocking shell.
*
fn io.input
not documented: see
io module
*
fn io.open
not documented: see
io module
*
fn io.type
not documented: see
io module
*
fn io.tmpfile
not documented: see
io module
*
fn io.close
not documented: see
io module
*
fn io.lines
not documented: see
io module
*
fn io.write
not documented: see
io module
*
fn io.read
not documented: see
io module
*
fn io.output
not documented: see
io module
*
fn io.flush
not documented: see
io module
*
fn os.execute(string) -> (ok, "exit", rc)
Execute shell command via C's `system` API. Returns:
- ok: true on command success, false if rc>0
- "exit": always literal "exit" if command completed
- rc: the return code of the command
os.execute'shell command' -> (ok, "exit", rc)
os.execute() -> isShellAvailable
Prints whatever was executed. There are no ways to
redirect the output besides piping in the command
string itself.
Recommendation:
For all but the simplest cases use io.popen instead
*
fn os.exit
not documented: see
os module
*
fn os.clock
not documented: see
os module
*
fn os.getenv
not documented: see
os module
*
fn os.tmpname
not documented: see
os module
*
fn os.setlocale
not documented: see
os module
*
fn os.rename
not documented: see
os module
*
fn os.date
not documented: see
os module
*
fn os.remove(path) -> nil
remove file.
*
fn os.time
not documented: see
os module
*
fn os.difftime
not documented: see
os module
*
fn math.type(v) -> ("float" | "integer" | nil)
*
fn math.max(x, ...) -> max according to [$<]
*
fn math.min(x, ...) -> min according to [$<]
*
fn math.cos(x) -> cos(x) in radians
*
fn math.sin(x) -> sin(x) in radians
*
fn math.tan(x) -> tan(x) in radians
*
fn math.acos(x) -> arccos(x) in radians
*
fn math.asin(x) -> arcsin(x) in radians
*
fn math.atan2(n, d) -> arctan(n / d) in radians
*
fn math.exp(x) -> e^x (where e is the natural log base)
*
fn math.abs
currently not documented
*
fn math.ceil
currently not documented
*
fn math.atan2(n, d) -> arctan(n / d) in radians
*
fn math.deg
currently not documented
*
fn math.tanh
currently not documented
*
fn math.floor
currently not documented
*
fn math.randomseed
currently not documented
*
fn math.ldexp
currently not documented
*
fn math.cosh
currently not documented
*
fn math.sqrt
currently not documented
*
fn math.tointeger
currently not documented
*
fn math.rad
currently not documented
*
fn math.log10
currently not documented
*
fn math.log
currently not documented
*
fn math.modf
currently not documented
*
fn math.ult
currently not documented
*
fn math.random
currently not documented
*
fn math.sinh
currently not documented
*
fn math.fmod
currently not documented
*
fn math.frexp
currently not documented
*
fn math.pow
currently not documented
*
fn for()
for is a looping construct with two forms:
Numeric:
for i=si,ei,period do -- period=1 by default
... do something with i
end
-- is basically the same as
local i = si
while i <= ei do i = i + si
... do something with i
end
Generic:
for i, v, etc in (nextfn, state, _index) do
.. do something with i, v, ...
end
-- is almost the same as
while true do
local i, v, etc = nextfn(state, _index)
if i == nil then break end
_index = i -- note: C internal, _index from lua doesn't change
... code using i, v, etc here
end
The goal in writing a stateless iterator function is to match this
loop's API as much as possible.
Example rewriting ipairs:
local function rawipairs(t, i)
i = i + 1
if i > #t then return nil end
return i, t[i]
end
local function myipairs_(t)
return rawipairs, t, 0
end
for i, v in myipairs{5, 6, 7} do
iterates through (1, 5) -> (2, 6) -> (3, 7)
end
Example rewriting pairs using
next(t, key):
function mypairs(t)
return next, t, nil
end
for k, v in mypairs{a=1, b=2, c=3} do
iterates through ('a', 1) -> ('b', 2) -> ('c', 3)
end
See also: metaty.split is a more complex example.