+Trace function calls Use as debug.sethook (trace, "cr"), which is done automatically when _DEBUG.call is set. Based on test/trace-calls.lua from the Lua distribution.
+
+
+
Parameters
+
+
+
+ event: event causing the call
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Tables
+
+
+
_DEBUG
+
To activate debugging set _DEBUG either to any true value (equivalent to {level = 1}), or as documented below.
+
+
+Fields
+
+
+
+ level: debugging level
+
+
+
+ call: do call trace debugging
+
+
+
+ std: do standard library debugging (run examples & test code)
+
+ stop_at_nonopt: if true, stop option processing at first non-option
+
+
+
+
+
+
+
+
+
+
Return values:
+
+
+
table of remaining non-options
+
+
table of option key-value list pairs
+
+
table of error messages
+
+
+
+
+
+
+
+
+
+
+
makeOptions (t)
+
+Options table constructor: adds lookup tables for the option names
+
+
+
Parameters
+
+
+
+ t:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
processArgs (prog, ...)
+
+Simple getOpt wrapper. If the caller didn't supply their own already, adds --version/-V and --help/-h options automatically; stops program if there was an error, or if --help or --version was used.
+
+
+
+Concatenate two or more directories into a path, removing the trailing slash.
+
+
+
Parameters
+
+
+
+ ...: path components
+
+
+
+
+
+
+
+
+
+
Return value:
+path
+
+
+
+
+
+
+
+
+
catfile (...)
+
+Concatenate one or more directories and a filename into a path.
+
+
+
Parameters
+
+
+
+ ...: path components
+
+
+
+
+
+
+
+
+
+
Return value:
+path
+
+
+
+
+
+
+
+
+
processFiles (f)
+
+Process files specified on the command-line. If no files given, process io.stdin; in list of files, - means io.stdin. FIXME: Make the file list an argument to the function.
+
+
+
Parameters
+
+
+
+ f: function to process files with, which is passed (name, arg_no)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
readlines (h)
+
+Read a file or file handle into a list of lines.
+
+
+
Parameters
+
+
+
+ h: file handle or name (default: io.input ()); if h is a handle, the file is closed after reading
+
+
+
+
+
+
+
+
+
+
Return value:
+list of lines
+
+
+
+
+
+
+
+
+
shell (c)
+
+Perform a shell command and return its output.
+
+
+
Parameters
+
+
+
+ c: command
+
+
+
+
+
+
+
+
+
+
Return value:
+output, or nil if error
+
+
+
+
+
+
+
+
+
slurp (h)
+
+Slurp a file handle.
+
+
+
Parameters
+
+
+
+ h: file handle or name (default: io.input ())
+
+
+
+
+
+
+
+
+
+
Return value:
+contents of file or handle, or nil if error
+
+
+
+
+
+
+
+
+
splitdir (path)
+
+Split a directory path into components. Empty components are retained: the root directory becomes {"", ""}.
+
+
+
Find the longest common subsequence of two sequences.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Functions
+
+
+
+
+
longestCommonSubseq (a, b, s)
+
+Find the longest common subsequence of two sequences. The sequence objects must have an __append metamethod. This is provided by string_ext for strings, and by list for lists.
+
+
+
Parameters
+
+
+
+ a: first sequence
+
+
+
+ b: second sequence
+
+
+
+ s: an empty sequence of the same type, to hold the result
+
+Turn a list of pairs into a table. FIXME: Find a better name.
+
+
+
Parameters
+
+
+
+ ls: list {{i1, v1}, ..., {in, vn}}
+
+
+
+
+
+
+
+
+
+
Return value:
+table {i1=v1, ..., in=vn}
+
+
+
+
+
+
+
+
+
elems (l)
+
+An iterator over the elements of a list.
+
+
+
Parameters
+
+
+
+ l: list to iterate over
+
+
+
+
+
+
+
+
+
+
Return values:
+
+
+
iterator function which returns successive elements of the list
+
+
the list l as above
+
+
true
+
+
+
+
+
+
+
+
+
+
+
enpair (t)
+
+Turn a table into a list of pairs. FIXME: Find a better name.
+
+
+
Parameters
+
+
+
+ t: table {i1=v1, ..., in=vn}
+
+
+
+
+
+
+
+
+
+
Return value:
+list {{i1, v1}, ..., {in, vn}}
+
+
+
+
+
+
+
+
+
filter (p, l)
+
+Filter a list according to a predicate.
+
+
+
Parameters
+
+
+
+ p: predicate (function of one argument returning a boolean)
+
+
+
+ l: list of lists
+
+
+
+
+
+
+
+
+
+
Return value:
+result list containing elements e of l for which p (e) is true
+
+
+
+
+
+
+
+
+
flatten (l)
+
+Flatten a list.
+
+
+
Parameters
+
+
+
+ l: list to flatten
+
+
+
+
+
+
+
+
+
+
Return value:
+flattened list
+
+
+
+
+
+
+
+
+
foldl (f, e, l)
+
+Fold a binary function through a list left associatively.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ e: element to place in left-most position
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result
+
+
+
+
+
+
+
+
+
foldr (f, e, l)
+
+Fold a binary function through a list right associatively.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ e: element to place in right-most position
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result
+
+
+
+
+
+
+
+
+
indexKey (f, l)
+
+Make an index of a list of tables on a given field
+
+
+
Parameters
+
+
+
+ f: field
+
+
+
+ l: list of tables {t1, ..., tn}
+
+
+
+
+
+
+
+
+
+
Return value:
+index {t1[f]=1, ..., tn[f]=n}
+
+
+
+
+
+
+
+
+
indexValue (f, l)
+
+Copy a list of tables, indexed on a given field
+
+
+
Parameters
+
+
+
+ f: field whose value should be used as index
+
+
+
+ l: list of tables {i1=t1, ..., in=tn}
+
+
+
+
+
+
+
+
+
+
Return value:
+index {t1[f]=t1, ..., tn[f]=tn}
+
+
+
+
+
+
+
+
+
map (f, l)
+
+Map a function over a list.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result list {f (l[1]), ..., f (l[#l])}
+
+
+
+
+
+
+
+
+
mapWith (f, l, ls)
+
+Map a function over a list of lists.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ l:
+
+
+
+ ls: list of lists
+
+
+
+
+
+
+
+
+
+
Return value:
+result list {f (unpack (ls[1]))), ..., f (unpack (ls[#ls]))}
+
+
+
+
+
+
+
+
+
new (l, t)
+
+List constructor. Needed in order to use metamethods.
+
+
+
Parameters
+
+
+
+ l:
+
+
+
+ t: list (as a table), or nil for empty list
+
+
+
+
+
+
+
+
+
+
Return value:
+list (with list metamethods)
+
+
+
+
+
+
+
+
+
project (f, l)
+
+Project a list of fields from a list of tables.
+
+
+
Parameters
+
+
+
+ f: field to project
+
+
+
+ l: list of tables
+
+
+
+
+
+
+
+
+
+
Return value:
+list of f fields
+
+
+
+
+
+
+
+
+
relems (l)
+
+An iterator over the elements of a list, in reverse.
+
+
+
Parameters
+
+
+
+ l: list to iterate over
+
+
+
+
+
+
+
+
+
+
Return values:
+
+
+
iterator function which returns precessive elements of the list
+
+
the list l as above
+
+
true
+
+
+
+
+
+
+
+
+
+
+
rep (l, n)
+
+Repeat a list.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+ n: number of times to repeat
+
+
+
+
+
+
+
+
+
+
Return value:
+n copies of l appended together
+
+
+
+
+
+
+
+
+
reverse (l)
+
+Reverse a list.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+list {l[#l], ..., l[1]}
+
+
+
+
+
+
+
+
+
shape (s, l)
+
+Shape a list according to a list of dimensions. Dimensions are given outermost first and items from the original list are distributed breadth first; there may be one 0 indicating an indefinite number. Hence, {0} is a flat list, {1} is a singleton, {2, 0} is a list of two lists, and {0, 2} is a list of pairs. Algorithm: turn shape into all positive numbers, calculating the zero if necessary and making sure there is at most one; recursively walk the shape, adding empty tables until the bottom level is reached at which point add table items instead, using a counter to walk the flattened original list.
+
+
+
Parameters
+
+
+
+ s: {d1, ..., dn}
+
+
+
+ l: list to reshape
+
+
+
+
+
+
+
+
+
+
Return value:
+reshaped list FIXME: Use ileaves instead of flatten (needs a while instead of a for in fill function)
+
+
+
+
+
+
+
+
+
sub (l, from, to)
+
+Return a sub-range of a list. (The equivalent of string.sub on strings; negative list indices count from the end of the list.)
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+ from: start of range (default: 1)
+
+
+
+ to: end of range (default: #l)
+
+
+
+
+
+
+
+
+
+
Return value:
+{l[from], ..., l[to]}
+
+
+
+
+
+
+
+
+
tail (l)
+
+Return a list with its first element removed.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+{l[2], ..., l[#l]}
+
+
+
+
+
+
+
+
+
transpose (ls)
+
+Transpose a list of lists. This function in Lua is equivalent to zip and unzip in more strongly typed languages.
+
+
+
+Trace function calls Use as debug.sethook (trace, "cr"), which is done automatically when _DEBUG.call is set. Based on test/trace-calls.lua from the Lua distribution.
+
+
+
Parameters
+
+
+
+ event: event causing the call
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Tables
+
+
+
_DEBUG
+
To activate debugging set _DEBUG either to any true value (equivalent to {level = 1}), or as documented below.
+
+
+Fields
+
+
+
+ level: debugging level
+
+
+
+ call: do call trace debugging
+
+
+
+ std: do standard library debugging (run examples & test code)
+
Tables mapped to the filing system Only string keys are permitted; package.dirsep characters are converted to underscores. Values are stored as strings (converted by tostring). As with disk operations, a table's elements must be set to nil (deleted) before the table itself can be set to nil.
+Options table constructor: adds lookup tables for the option names
+
+
+
Parameters
+
+
+
+ t:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
processArgs ()
+
+Simple getOpt wrapper. Adds -version/-V and -help/-h automatically; stops program if there was an error, or if -help or -version was used.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
usage ()
+
+Emit a usage message.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
usageInfo (header, optDesc, pageWidth)
+
+Produce usage info for the given options
+
+
+
Parameters
+
+
+
+ header: header string
+
+
+
+ optDesc: option descriptors
+
+
+
+ pageWidth: width to format to [78]
+
+
+
+
+
+
+
+
+
+
Return value:
+formatted string
+
+
+
+
+
+
+
+
+
+
+
+
Tables
+
+
+
_G.Option
+
Options table type.
+
+
+Fields
+
+
+
+ name: list of names
+
+
+
+ desc: description of this option
+
+
+
+ type: type of argument (if any): Req(uired), Opt(ional)
+
+Concatenate two or more directories into a path, removing the trailing slash.
+
+
+
Parameters
+
+
+
+ ...: path components
+
+
+
+
+
+
+
+
+
+
Return value:
+path
+
+
+
+
+
+
+
+
+
catfile (...)
+
+Concatenate one or more directories and a filename into a path.
+
+
+
Parameters
+
+
+
+ ...: path components
+
+
+
+
+
+
+
+
+
+
Return value:
+path
+
+
+
+
+
+
+
+
+
processFiles (f)
+
+Process files specified on the command-line. If no files given, process io.stdin; in list of files, - means io.stdin. FIXME: Make the file list an argument to the function.
+
+
+
Parameters
+
+
+
+ f: function to process files with, which is passed (name, arg_no)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
readlines (h)
+
+Read a file or file handle into a list of lines.
+
+
+
Parameters
+
+
+
+ h: file handle or name (default: io.input ()); if h is a handle, the file is closed after reading
+
+
+
+
+
+
+
+
+
+
Return value:
+list of lines
+
+
+
+
+
+
+
+
+
shell (c)
+
+Perform a shell command and return its output.
+
+
+
Parameters
+
+
+
+ c: command
+
+
+
+
+
+
+
+
+
+
Return value:
+output, or nil if error
+
+
+
+
+
+
+
+
+
slurp (h)
+
+Slurp a file handle.
+
+
+
Parameters
+
+
+
+ h: file handle or name (default: io.input ())
+
+
+
+
+
+
+
+
+
+
Return value:
+contents of file or handle, or nil if error
+
+
+
+
+
+
+
+
+
splitdir (path)
+
+Split a directory path into components. Empty components are retained: the root directory becomes {"", ""}.
+
+
+
Find the longest common subsequence of two sequences.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Functions
+
+
+
+
+
longestCommonSubseq (a, b, s)
+
+Find the longest common subsequence of two sequences. The sequence objects must have an __append metamethod. This is provided by string_ext for strings, and by list for lists.
+
+
+
Parameters
+
+
+
+ a: first sequence
+
+
+
+ b: second sequence
+
+
+
+ s: an empty sequence of the same type, to hold the result
+
+Turn a list of pairs into a table. FIXME: Find a better name.
+
+
+
Parameters
+
+
+
+ ls: list {{i1, v1}, ..., {in, vn}}
+
+
+
+
+
+
+
+
+
+
Return value:
+table {i1=v1, ..., in=vn}
+
+
+
+
+
+
+
+
+
elems (l)
+
+An iterator over the elements of a list.
+
+
+
Parameters
+
+
+
+ l: list to iterate over
+
+
+
+
+
+
+
+
+
+
Return values:
+
+
+
iterator function which returns successive elements of the list
+
+
the list l as above
+
+
true
+
+
+
+
+
+
+
+
+
+
+
enpair (t)
+
+Turn a table into a list of pairs. FIXME: Find a better name.
+
+
+
Parameters
+
+
+
+ t: table {i1=v1, ..., in=vn}
+
+
+
+
+
+
+
+
+
+
Return value:
+list {{i1, v1}, ..., {in, vn}}
+
+
+
+
+
+
+
+
+
filter (p, l)
+
+Filter a list according to a predicate.
+
+
+
Parameters
+
+
+
+ p: predicate (function of one argument returning a boolean)
+
+
+
+ l: list of lists
+
+
+
+
+
+
+
+
+
+
Return value:
+result list containing elements e of l for which p (e) is true
+
+
+
+
+
+
+
+
+
flatten (l)
+
+Flatten a list.
+
+
+
Parameters
+
+
+
+ l: list to flatten
+
+
+
+
+
+
+
+
+
+
Return value:
+flattened list
+
+
+
+
+
+
+
+
+
foldl (f, e, l)
+
+Fold a binary function through a list left associatively.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ e: element to place in left-most position
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result
+
+
+
+
+
+
+
+
+
foldr (f, e, l)
+
+Fold a binary function through a list right associatively.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ e: element to place in right-most position
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result
+
+
+
+
+
+
+
+
+
indexKey (f, l)
+
+Make an index of a list of tables on a given field
+
+
+
Parameters
+
+
+
+ f: field
+
+
+
+ l: list of tables {t1, ..., tn}
+
+
+
+
+
+
+
+
+
+
Return value:
+index {t1[f]=1, ..., tn[f]=n}
+
+
+
+
+
+
+
+
+
indexValue (f, l)
+
+Copy a list of tables, indexed on a given field
+
+
+
Parameters
+
+
+
+ f: field whose value should be used as index
+
+
+
+ l: list of tables {i1=t1, ..., in=tn}
+
+
+
+
+
+
+
+
+
+
Return value:
+index {t1[f]=t1, ..., tn[f]=tn}
+
+
+
+
+
+
+
+
+
map (f, l)
+
+Map a function over a list.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+result list {f (l[1]), ..., f (l[#l])}
+
+
+
+
+
+
+
+
+
mapWith (f, l, ls)
+
+Map a function over a list of lists.
+
+
+
Parameters
+
+
+
+ f: function
+
+
+
+ l:
+
+
+
+ ls: list of lists
+
+
+
+
+
+
+
+
+
+
Return value:
+result list {f (unpack (ls[1]))), ..., f (unpack (ls[#ls]))}
+
+
+
+
+
+
+
+
+
new (l, t)
+
+List constructor. Needed in order to use metamethods.
+
+
+
Parameters
+
+
+
+ l:
+
+
+
+ t: list (as a table)
+
+
+
+
+
+
+
+
+
+
Return value:
+list (with list metamethods)
+
+
+
+
+
+
+
+
+
project (f, l)
+
+Project a list of fields from a list of tables.
+
+
+
Parameters
+
+
+
+ f: field to project
+
+
+
+ l: list of tables
+
+
+
+
+
+
+
+
+
+
Return value:
+list of f fields
+
+
+
+
+
+
+
+
+
relems (l)
+
+An iterator over the elements of a list, in reverse.
+
+
+
Parameters
+
+
+
+ l: list to iterate over
+
+
+
+
+
+
+
+
+
+
Return values:
+
+
+
iterator function which returns precessive elements of the list
+
+
the list l as above
+
+
true
+
+
+
+
+
+
+
+
+
+
+
rep (l, n)
+
+Repeat a list.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+ n: number of times to repeat
+
+
+
+
+
+
+
+
+
+
Return value:
+n copies of l appended together
+
+
+
+
+
+
+
+
+
reverse (l)
+
+Reverse a list.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+list {l[#l], ..., l[1]}
+
+
+
+
+
+
+
+
+
shape (s, l)
+
+Shape a list according to a list of dimensions. Dimensions are given outermost first and items from the original list are distributed breadth first; there may be one 0 indicating an indefinite number. Hence, {0} is a flat list, {1} is a singleton, {2, 0} is a list of two lists, and {0, 2} is a list of pairs. Algorithm: turn shape into all positive numbers, calculating the zero if necessary and making sure there is at most one; recursively walk the shape, adding empty tables until the bottom level is reached at which point add table items instead, using a counter to walk the flattened original list.
+
+
+
Parameters
+
+
+
+ s: {d1, ..., dn}
+
+
+
+ l: list to reshape
+
+
+
+
+
+
+
+
+
+
Return value:
+reshaped list FIXME: Use ileaves instead of flatten (needs a while instead of a for in fill function)
+
+
+
+
+
+
+
+
+
slice (l, from, to)
+
+Return a slice of a list. (Negative list indices count from the end of the list.)
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+ from: start of slice (default: 1)
+
+
+
+ to: end of slice (default: #l)
+
+
+
+
+
+
+
+
+
+
Return value:
+{l[from], ..., l[to]}
+
+
+
+
+
+
+
+
+
tail (l)
+
+Return a list with its first element removed.
+
+
+
Parameters
+
+
+
+ l: list
+
+
+
+
+
+
+
+
+
+
Return value:
+{l[2], ..., l[#l]}
+
+
+
+
+
+
+
+
+
transpose (ls)
+
+Transpose a list of lists. This function in Lua is equivalent to zip and unzip in more strongly typed languages.
+
+
+
where each nodei is a symbolic name, and list is the list of trees returned if the corresponding token was a list token.
A grammar is a table of rules of the form
non-terminal = {production1, production2, ...}
plus a special item
lexemes = Set {"class1", "class2", ...}
Each production gives a form that a non-terminal may take. A production has the form
production = {"token1", "token2", ..., [action][,abstract]}
A production
must not start with the non-terminal being defined (it must not be left-recursive)
must not be a prefix of a later production in the same non-terminal
Each token may be
a non-terminal, i.e. a token defined by the grammar
an optional symbol is indicated by the suffix _opt
a list is indicated by the suffix _list, and may be followed by _≤separator-symbol> (default is no separator)
a lexeme class
a string to match literally
The parse tree for a literal string or lexeme class is the string that was matched. The parse tree for a non-terminal is a table of the form
{ty = "non_terminal_name", tree1, tree2, ...}
where the treei are the parse trees for the corresponding terminals and non-terminals.
An action is of the form
action = function (tree, token, pos) ... return tree_ end
It is passed the parse tree for the current node, the token list, and the current position in the token list, and returns a new parse tree.
An abstract syntax rule is of the form
name = {i1, i2, ...}
where i1, i2, ... are numbers. This results in a parse tree of the form
{ty = "name"; treei1, treei2, ...}
If a production has no abstract syntax rule, the result is the parse node for the current node.
FIXME: Give lexemes as an extra argument to Parser? FIXME: Rename second argument to parse method to "tokens"? FIXME: Make start_token an optional argument to parse? (swap with token list) and have it default to the first non-terminal?
TODO: Write a style guide (indenting/wrapping, capitalisation, function and variable names); library functions should call error, not die; OO vs non-OO (a thorny problem).
TODO: Add tests for each function immediately after the function; this also helps to check module dependencies.
+
+
+ std.list
+ new list containing {l[#l], ..., l[1]}
+
+
+
+
+
+
+
+
+ std.list:shape (l, s)
+
+
+ Shape a list according to a list of dimensions.
+
+
Dimensions are given outermost first and items from the original
+ list are distributed breadth first; there may be one 0 indicating
+ an indefinite number. Hence, {0} is a flat list,
+ {1} is a singleton, {2, 0} is a list of
+ two lists, and {0, 2} is a list of pairs.
+
+
Algorithm: turn shape into all positive numbers, calculating
+ the zero if necessary and making sure there is at most one;
+ recursively walk the shape, adding empty tables until the bottom
+ level is reached at which point add table items instead, using a
+ counter to walk the flattened original list.
+
+
This module creates the root prototype object from which every other
+ object is descended. There are no classes as such, rather new objects
+ are created by cloning an existing prototype object, and then changing
+ or adding to it. Further objects can then be made by cloning the changed
+ object, and so on.
+
+
Objects are cloned by simply calling an existing object which then
+ serves as a prototype, from which the new object is copied.
+
+
All valid objects contain a field _init, which determines the syntax
+ required to execute the cloning process:
+
+
+
_init can be a list of keys; then the unnamed init_1 through
+ init_n values from the argument table are assigned to the
+ corresponding keys in new_object;
Or it can be a function, in which the arguments passed to the
+ prototype during cloning are simply handed to the _init function:
+
+
new_object = prototype (value, ...)
+
+
+
+
Field names beginning with "_" are private, and moved into the object
+ metatable during cloning. Unless new_object changes the metatable this
+ way, then it will share a metatable with prototype for efficiency.
+
+
Objects, then, are essentially tables of field_n = value_n pairs:
+
+
+
Access an object field: object.field
+
Call an object method: object:method (...)
+
Call a "class" method: Class.method (object, ...)
+
Add a field: object.field = x
+
Add a method: function object:method (...) ... end
+ Return a shallow copy of non-private object fields.
+
+
This pseudo-metamethod is used during object cloning to make the
+ intial new object table, and can be overridden in other objects
+ for greater control of which fields are considered non-private.
+
+
+
+
+
+
+
+ std.object
+ a clone of prototype, adjusted
+ according to the rules above, and sharing a metatable where possible.
+
+
+
+
+
+
+
+
+ std.object:tostring (o)
+
+
+ Return a stringified version of the contents of object.
+
+
First the object type, and then between { and } a list of the array
+ part of the object table (without numeric keys) followed by the
+ remaining key-value pairs.
+
+
This function doesn't recurse explicity, but relies upon suitable
+ __tostring metamethods in contained objects.
+
+
-Trace function calls Use as debug.sethook (trace, "cr"), which is done automatically when _DEBUG.call is set. Based on test/trace-calls.lua from the Lua distribution.
-
-
-
Parameters
-
-
-
- event: event causing the call
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Tables
-
-
-
_DEBUG
-
To activate debugging set _DEBUG either to any true value (equivalent to {level = 1}), or as documented below.
-
-
-Fields
-
-
-
- level: debugging level
-
-
-
- call: do call trace debugging
-
-
-
- std: do standard library debugging (run examples & test code)
-
- stop_at_nonopt: if true, stop option processing at first non-option
-
-
-
-
-
-
-
-
-
-
Return values:
-
-
-
table of remaining non-options
-
-
table of option key-value list pairs
-
-
table of error messages
-
-
-
-
-
-
-
-
-
-
-
makeOptions (t)
-
-Options table constructor: adds lookup tables for the option names
-
-
-
Parameters
-
-
-
- t:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
processArgs (prog, ...)
-
-Simple getOpt wrapper. If the caller didn't supply their own already, adds --version/-V and --help/-h options automatically; stops program if there was an error, or if --help or --version was used.
-
-
-
-Concatenate two or more directories into a path, removing the trailing slash.
-
-
-
Parameters
-
-
-
- ...: path components
-
-
-
-
-
-
-
-
-
-
Return value:
-path
-
-
-
-
-
-
-
-
-
catfile (...)
-
-Concatenate one or more directories and a filename into a path.
-
-
-
Parameters
-
-
-
- ...: path components
-
-
-
-
-
-
-
-
-
-
Return value:
-path
-
-
-
-
-
-
-
-
-
processFiles (f)
-
-Process files specified on the command-line. If no files given, process io.stdin; in list of files, - means io.stdin. FIXME: Make the file list an argument to the function.
-
-
-
Parameters
-
-
-
- f: function to process files with, which is passed (name, arg_no)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
readlines (h)
-
-Read a file or file handle into a list of lines.
-
-
-
Parameters
-
-
-
- h: file handle or name (default: io.input ()); if h is a handle, the file is closed after reading
-
-
-
-
-
-
-
-
-
-
Return value:
-list of lines
-
-
-
-
-
-
-
-
-
shell (c)
-
-Perform a shell command and return its output.
-
-
-
Parameters
-
-
-
- c: command
-
-
-
-
-
-
-
-
-
-
Return value:
-output, or nil if error
-
-
-
-
-
-
-
-
-
slurp (h)
-
-Slurp a file handle.
-
-
-
Parameters
-
-
-
- h: file handle or name (default: io.input ())
-
-
-
-
-
-
-
-
-
-
Return value:
-contents of file or handle, or nil if error
-
-
-
-
-
-
-
-
-
splitdir (path)
-
-Split a directory path into components. Empty components are retained: the root directory becomes {"", ""}.
-
-
-
Find the longest common subsequence of two sequences.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Functions
-
-
-
-
-
longestCommonSubseq (a, b, s)
-
-Find the longest common subsequence of two sequences. The sequence objects must have an __append metamethod. This is provided by string_ext for strings, and by list for lists.
-
-
-
Parameters
-
-
-
- a: first sequence
-
-
-
- b: second sequence
-
-
-
- s: an empty sequence of the same type, to hold the result
-
-Turn a list of pairs into a table. FIXME: Find a better name.
-
-
-
Parameters
-
-
-
- ls: list {{i1, v1}, ..., {in, vn}}
-
-
-
-
-
-
-
-
-
-
Return value:
-table {i1=v1, ..., in=vn}
-
-
-
-
-
-
-
-
-
elems (l)
-
-An iterator over the elements of a list.
-
-
-
Parameters
-
-
-
- l: list to iterate over
-
-
-
-
-
-
-
-
-
-
Return values:
-
-
-
iterator function which returns successive elements of the list
-
-
the list l as above
-
-
true
-
-
-
-
-
-
-
-
-
-
-
enpair (t)
-
-Turn a table into a list of pairs. FIXME: Find a better name.
-
-
-
Parameters
-
-
-
- t: table {i1=v1, ..., in=vn}
-
-
-
-
-
-
-
-
-
-
Return value:
-list {{i1, v1}, ..., {in, vn}}
-
-
-
-
-
-
-
-
-
filter (p, l)
-
-Filter a list according to a predicate.
-
-
-
Parameters
-
-
-
- p: predicate (function of one argument returning a boolean)
-
-
-
- l: list of lists
-
-
-
-
-
-
-
-
-
-
Return value:
-result list containing elements e of l for which p (e) is true
-
-
-
-
-
-
-
-
-
flatten (l)
-
-Flatten a list.
-
-
-
Parameters
-
-
-
- l: list to flatten
-
-
-
-
-
-
-
-
-
-
Return value:
-flattened list
-
-
-
-
-
-
-
-
-
foldl (f, e, l)
-
-Fold a binary function through a list left associatively.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- e: element to place in left-most position
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result
-
-
-
-
-
-
-
-
-
foldr (f, e, l)
-
-Fold a binary function through a list right associatively.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- e: element to place in right-most position
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result
-
-
-
-
-
-
-
-
-
indexKey (f, l)
-
-Make an index of a list of tables on a given field
-
-
-
Parameters
-
-
-
- f: field
-
-
-
- l: list of tables {t1, ..., tn}
-
-
-
-
-
-
-
-
-
-
Return value:
-index {t1[f]=1, ..., tn[f]=n}
-
-
-
-
-
-
-
-
-
indexValue (f, l)
-
-Copy a list of tables, indexed on a given field
-
-
-
Parameters
-
-
-
- f: field whose value should be used as index
-
-
-
- l: list of tables {i1=t1, ..., in=tn}
-
-
-
-
-
-
-
-
-
-
Return value:
-index {t1[f]=t1, ..., tn[f]=tn}
-
-
-
-
-
-
-
-
-
map (f, l)
-
-Map a function over a list.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result list {f (l[1]), ..., f (l[#l])}
-
-
-
-
-
-
-
-
-
mapWith (f, l, ls)
-
-Map a function over a list of lists.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- l:
-
-
-
- ls: list of lists
-
-
-
-
-
-
-
-
-
-
Return value:
-result list {f (unpack (ls[1]))), ..., f (unpack (ls[#ls]))}
-
-
-
-
-
-
-
-
-
new (l, t)
-
-List constructor. Needed in order to use metamethods.
-
-
-
Parameters
-
-
-
- l:
-
-
-
- t: list (as a table), or nil for empty list
-
-
-
-
-
-
-
-
-
-
Return value:
-list (with list metamethods)
-
-
-
-
-
-
-
-
-
project (f, l)
-
-Project a list of fields from a list of tables.
-
-
-
Parameters
-
-
-
- f: field to project
-
-
-
- l: list of tables
-
-
-
-
-
-
-
-
-
-
Return value:
-list of f fields
-
-
-
-
-
-
-
-
-
relems (l)
-
-An iterator over the elements of a list, in reverse.
-
-
-
Parameters
-
-
-
- l: list to iterate over
-
-
-
-
-
-
-
-
-
-
Return values:
-
-
-
iterator function which returns precessive elements of the list
-
-
the list l as above
-
-
true
-
-
-
-
-
-
-
-
-
-
-
rep (l, n)
-
-Repeat a list.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
- n: number of times to repeat
-
-
-
-
-
-
-
-
-
-
Return value:
-n copies of l appended together
-
-
-
-
-
-
-
-
-
reverse (l)
-
-Reverse a list.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-list {l[#l], ..., l[1]}
-
-
-
-
-
-
-
-
-
shape (s, l)
-
-Shape a list according to a list of dimensions. Dimensions are given outermost first and items from the original list are distributed breadth first; there may be one 0 indicating an indefinite number. Hence, {0} is a flat list, {1} is a singleton, {2, 0} is a list of two lists, and {0, 2} is a list of pairs. Algorithm: turn shape into all positive numbers, calculating the zero if necessary and making sure there is at most one; recursively walk the shape, adding empty tables until the bottom level is reached at which point add table items instead, using a counter to walk the flattened original list.
-
-
-
Parameters
-
-
-
- s: {d1, ..., dn}
-
-
-
- l: list to reshape
-
-
-
-
-
-
-
-
-
-
Return value:
-reshaped list FIXME: Use ileaves instead of flatten (needs a while instead of a for in fill function)
-
-
-
-
-
-
-
-
-
sub (l, from, to)
-
-Return a sub-range of a list. (The equivalent of string.sub on strings; negative list indices count from the end of the list.)
-
-
-
Parameters
-
-
-
- l: list
-
-
-
- from: start of range (default: 1)
-
-
-
- to: end of range (default: #l)
-
-
-
-
-
-
-
-
-
-
Return value:
-{l[from], ..., l[to]}
-
-
-
-
-
-
-
-
-
tail (l)
-
-Return a list with its first element removed.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-{l[2], ..., l[#l]}
-
-
-
-
-
-
-
-
-
transpose (ls)
-
-Transpose a list of lists. This function in Lua is equivalent to zip and unzip in more strongly typed languages.
-
-
-
-Trace function calls Use as debug.sethook (trace, "cr"), which is done automatically when _DEBUG.call is set. Based on test/trace-calls.lua from the Lua distribution.
-
-
-
Parameters
-
-
-
- event: event causing the call
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Tables
-
-
-
_DEBUG
-
To activate debugging set _DEBUG either to any true value (equivalent to {level = 1}), or as documented below.
-
-
-Fields
-
-
-
- level: debugging level
-
-
-
- call: do call trace debugging
-
-
-
- std: do standard library debugging (run examples & test code)
-
Tables mapped to the filing system Only string keys are permitted; package.dirsep characters are converted to underscores. Values are stored as strings (converted by tostring). As with disk operations, a table's elements must be set to nil (deleted) before the table itself can be set to nil.
-Options table constructor: adds lookup tables for the option names
-
-
-
Parameters
-
-
-
- t:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
processArgs ()
-
-Simple getOpt wrapper. Adds -version/-V and -help/-h automatically; stops program if there was an error, or if -help or -version was used.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
usage ()
-
-Emit a usage message.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
usageInfo (header, optDesc, pageWidth)
-
-Produce usage info for the given options
-
-
-
Parameters
-
-
-
- header: header string
-
-
-
- optDesc: option descriptors
-
-
-
- pageWidth: width to format to [78]
-
-
-
-
-
-
-
-
-
-
Return value:
-formatted string
-
-
-
-
-
-
-
-
-
-
-
-
Tables
-
-
-
_G.Option
-
Options table type.
-
-
-Fields
-
-
-
- name: list of names
-
-
-
- desc: description of this option
-
-
-
- type: type of argument (if any): Req(uired), Opt(ional)
-
-Concatenate two or more directories into a path, removing the trailing slash.
-
-
-
Parameters
-
-
-
- ...: path components
-
-
-
-
-
-
-
-
-
-
Return value:
-path
-
-
-
-
-
-
-
-
-
catfile (...)
-
-Concatenate one or more directories and a filename into a path.
-
-
-
Parameters
-
-
-
- ...: path components
-
-
-
-
-
-
-
-
-
-
Return value:
-path
-
-
-
-
-
-
-
-
-
processFiles (f)
-
-Process files specified on the command-line. If no files given, process io.stdin; in list of files, - means io.stdin. FIXME: Make the file list an argument to the function.
-
-
-
Parameters
-
-
-
- f: function to process files with, which is passed (name, arg_no)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
readlines (h)
-
-Read a file or file handle into a list of lines.
-
-
-
Parameters
-
-
-
- h: file handle or name (default: io.input ()); if h is a handle, the file is closed after reading
-
-
-
-
-
-
-
-
-
-
Return value:
-list of lines
-
-
-
-
-
-
-
-
-
shell (c)
-
-Perform a shell command and return its output.
-
-
-
Parameters
-
-
-
- c: command
-
-
-
-
-
-
-
-
-
-
Return value:
-output, or nil if error
-
-
-
-
-
-
-
-
-
slurp (h)
-
-Slurp a file handle.
-
-
-
Parameters
-
-
-
- h: file handle or name (default: io.input ())
-
-
-
-
-
-
-
-
-
-
Return value:
-contents of file or handle, or nil if error
-
-
-
-
-
-
-
-
-
splitdir (path)
-
-Split a directory path into components. Empty components are retained: the root directory becomes {"", ""}.
-
-
-
Find the longest common subsequence of two sequences.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Functions
-
-
-
-
-
longestCommonSubseq (a, b, s)
-
-Find the longest common subsequence of two sequences. The sequence objects must have an __append metamethod. This is provided by string_ext for strings, and by list for lists.
-
-
-
Parameters
-
-
-
- a: first sequence
-
-
-
- b: second sequence
-
-
-
- s: an empty sequence of the same type, to hold the result
-
-Turn a list of pairs into a table. FIXME: Find a better name.
-
-
-
Parameters
-
-
-
- ls: list {{i1, v1}, ..., {in, vn}}
-
-
-
-
-
-
-
-
-
-
Return value:
-table {i1=v1, ..., in=vn}
-
-
-
-
-
-
-
-
-
elems (l)
-
-An iterator over the elements of a list.
-
-
-
Parameters
-
-
-
- l: list to iterate over
-
-
-
-
-
-
-
-
-
-
Return values:
-
-
-
iterator function which returns successive elements of the list
-
-
the list l as above
-
-
true
-
-
-
-
-
-
-
-
-
-
-
enpair (t)
-
-Turn a table into a list of pairs. FIXME: Find a better name.
-
-
-
Parameters
-
-
-
- t: table {i1=v1, ..., in=vn}
-
-
-
-
-
-
-
-
-
-
Return value:
-list {{i1, v1}, ..., {in, vn}}
-
-
-
-
-
-
-
-
-
filter (p, l)
-
-Filter a list according to a predicate.
-
-
-
Parameters
-
-
-
- p: predicate (function of one argument returning a boolean)
-
-
-
- l: list of lists
-
-
-
-
-
-
-
-
-
-
Return value:
-result list containing elements e of l for which p (e) is true
-
-
-
-
-
-
-
-
-
flatten (l)
-
-Flatten a list.
-
-
-
Parameters
-
-
-
- l: list to flatten
-
-
-
-
-
-
-
-
-
-
Return value:
-flattened list
-
-
-
-
-
-
-
-
-
foldl (f, e, l)
-
-Fold a binary function through a list left associatively.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- e: element to place in left-most position
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result
-
-
-
-
-
-
-
-
-
foldr (f, e, l)
-
-Fold a binary function through a list right associatively.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- e: element to place in right-most position
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result
-
-
-
-
-
-
-
-
-
indexKey (f, l)
-
-Make an index of a list of tables on a given field
-
-
-
Parameters
-
-
-
- f: field
-
-
-
- l: list of tables {t1, ..., tn}
-
-
-
-
-
-
-
-
-
-
Return value:
-index {t1[f]=1, ..., tn[f]=n}
-
-
-
-
-
-
-
-
-
indexValue (f, l)
-
-Copy a list of tables, indexed on a given field
-
-
-
Parameters
-
-
-
- f: field whose value should be used as index
-
-
-
- l: list of tables {i1=t1, ..., in=tn}
-
-
-
-
-
-
-
-
-
-
Return value:
-index {t1[f]=t1, ..., tn[f]=tn}
-
-
-
-
-
-
-
-
-
map (f, l)
-
-Map a function over a list.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-result list {f (l[1]), ..., f (l[#l])}
-
-
-
-
-
-
-
-
-
mapWith (f, l, ls)
-
-Map a function over a list of lists.
-
-
-
Parameters
-
-
-
- f: function
-
-
-
- l:
-
-
-
- ls: list of lists
-
-
-
-
-
-
-
-
-
-
Return value:
-result list {f (unpack (ls[1]))), ..., f (unpack (ls[#ls]))}
-
-
-
-
-
-
-
-
-
new (l, t)
-
-List constructor. Needed in order to use metamethods.
-
-
-
Parameters
-
-
-
- l:
-
-
-
- t: list (as a table)
-
-
-
-
-
-
-
-
-
-
Return value:
-list (with list metamethods)
-
-
-
-
-
-
-
-
-
project (f, l)
-
-Project a list of fields from a list of tables.
-
-
-
Parameters
-
-
-
- f: field to project
-
-
-
- l: list of tables
-
-
-
-
-
-
-
-
-
-
Return value:
-list of f fields
-
-
-
-
-
-
-
-
-
relems (l)
-
-An iterator over the elements of a list, in reverse.
-
-
-
Parameters
-
-
-
- l: list to iterate over
-
-
-
-
-
-
-
-
-
-
Return values:
-
-
-
iterator function which returns precessive elements of the list
-
-
the list l as above
-
-
true
-
-
-
-
-
-
-
-
-
-
-
rep (l, n)
-
-Repeat a list.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
- n: number of times to repeat
-
-
-
-
-
-
-
-
-
-
Return value:
-n copies of l appended together
-
-
-
-
-
-
-
-
-
reverse (l)
-
-Reverse a list.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-list {l[#l], ..., l[1]}
-
-
-
-
-
-
-
-
-
shape (s, l)
-
-Shape a list according to a list of dimensions. Dimensions are given outermost first and items from the original list are distributed breadth first; there may be one 0 indicating an indefinite number. Hence, {0} is a flat list, {1} is a singleton, {2, 0} is a list of two lists, and {0, 2} is a list of pairs. Algorithm: turn shape into all positive numbers, calculating the zero if necessary and making sure there is at most one; recursively walk the shape, adding empty tables until the bottom level is reached at which point add table items instead, using a counter to walk the flattened original list.
-
-
-
Parameters
-
-
-
- s: {d1, ..., dn}
-
-
-
- l: list to reshape
-
-
-
-
-
-
-
-
-
-
Return value:
-reshaped list FIXME: Use ileaves instead of flatten (needs a while instead of a for in fill function)
-
-
-
-
-
-
-
-
-
slice (l, from, to)
-
-Return a slice of a list. (Negative list indices count from the end of the list.)
-
-
-
Parameters
-
-
-
- l: list
-
-
-
- from: start of slice (default: 1)
-
-
-
- to: end of slice (default: #l)
-
-
-
-
-
-
-
-
-
-
Return value:
-{l[from], ..., l[to]}
-
-
-
-
-
-
-
-
-
tail (l)
-
-Return a list with its first element removed.
-
-
-
Parameters
-
-
-
- l: list
-
-
-
-
-
-
-
-
-
-
Return value:
-{l[2], ..., l[#l]}
-
-
-
-
-
-
-
-
-
transpose (ls)
-
-Transpose a list of lists. This function in Lua is equivalent to zip and unzip in more strongly typed languages.
-
-
-
where each nodei is a symbolic name, and list is the list of trees returned if the corresponding token was a list token.
A grammar is a table of rules of the form
non-terminal = {production1, production2, ...}
plus a special item
lexemes = Set {"class1", "class2", ...}
Each production gives a form that a non-terminal may take. A production has the form
production = {"token1", "token2", ..., [action][,abstract]}
A production
must not start with the non-terminal being defined (it must not be left-recursive)
must not be a prefix of a later production in the same non-terminal
Each token may be
a non-terminal, i.e. a token defined by the grammar
an optional symbol is indicated by the suffix _opt
a list is indicated by the suffix _list, and may be followed by _≤separator-symbol> (default is no separator)
a lexeme class
a string to match literally
The parse tree for a literal string or lexeme class is the string that was matched. The parse tree for a non-terminal is a table of the form
{ty = "non_terminal_name", tree1, tree2, ...}
where the treei are the parse trees for the corresponding terminals and non-terminals.
An action is of the form
action = function (tree, token, pos) ... return tree_ end
It is passed the parse tree for the current node, the token list, and the current position in the token list, and returns a new parse tree.
An abstract syntax rule is of the form
name = {i1, i2, ...}
where i1, i2, ... are numbers. This results in a parse tree of the form
{ty = "name"; treei1, treei2, ...}
If a production has no abstract syntax rule, the result is the parse node for the current node.
FIXME: Give lexemes as an extra argument to Parser? FIXME: Rename second argument to parse method to "tokens"? FIXME: Make start_token an optional argument to parse? (swap with token list) and have it default to the first non-terminal?
+ Trace function calls.
+ Use as debug.sethook (trace, "cr"), which is done automatically
+ when _DEBUG.call is set.
+ Based on test/trace-calls.lua from the Lua distribution.
+
+
Parameters:
+
+
event
+ event causing the call
+
+
+
+
+
+
+
+
+
+
Tables
+
+
+
+ _DEBUG
+
+
+ To activate debugging set _DEBUG either to any true value
+ (equivalent to {level = 1}), or as documented below.
+
+
Fields:
+
+
level
+ debugging level
+
+
call
+ do call trace debugging
+
+
std
+ do standard library debugging (run examples & test code)
+
stop_at_nonopt
+ if true, stop option processing at first non-option
+
+
+
+
Returns:
+
+
+ table of remaining non-options
+
+ table of option key-value list pairs
+
+ table of error messages
+
+
+
+
+
+
+
+
+ processargs (prog, ...)
+
+
+ Simple getopt wrapper.
+ If the caller didn't supply their own already, -- adds --version/-V
+ and --help/-h options automatically;
+ stops program if there was an error, or if --help or --version was
+ used.
+
+
For backwards compatibility with older releases, require "std"
+ will inject the same functions into the global namespace as it
+ has done previously, even though it is now deprecated.
+
+
For new code, much better than scribbling all over the global
+ namespace, it's more hygienic to explicitly assign the results of
+ requiring just the submodules you actually use to a local variable,
+ and access its functions via that table.
TODO: Write a style guide (indenting/wrapping, capitalisation, function and variable names); library functions should call error, not die; OO vs non-OO (a thorny problem).
TODO: Add tests for each function immediately after the function; this also helps to check module dependencies.
All global variables must be 'declared' through a regular
+ assignment (even assigning nil will do) in a top-level
+ chunk before being used anywhere or assigned to inside a function.
+ From Lua distribution (etc/strict.lua).
Normally a cloned object will share its metatable with its prototype,
+ unless some new fields for the cloned object begin with '_', in which
+ case they are merged into a copy of the prototype metatable to form
+ a new metatable for the cloned object (and its clones).
+
+
params:
+
+
...
+ arguments for _init
+
+
+
+
+
+
+
+
+
+
+ std.object.__metatable
+
+
+ Metatable for objects.
+
+
This can't and shouldn't be set directly, because the Object class
+ manages it transparently during cloning.
+
+
Fields:
+
+
_type
+ string
+ derived objects can override this for objects
+ intended to be a prototype for further specialised objects.
+
+
_init
+ table or function
+ Derived objects can override this to be
+ a set of keys to use for assigning unnamed arguments, or a function
+ to that will be called with unnamed arguments durict cloning.
+
std.object
a clone of prototype, adjusted
- according to the rules above, and sharing a metatable where possible.
+ according to the rules above, and sharing a metatable where possible
+
Return a stringified version of the contents of object.
@@ -238,15 +300,8 @@
Returns:
remaining key-value pairs.
This function doesn't recurse explicity, but relies upon suitable
- __tostring metamethods in contained objects.
+ __tostring metamethods in contained objects.
-
- Extend tostring to work better on tables.
+ Extend tostring to work better on tables.
diff --git a/modules/std.io.html b/modules/std.io.html
index 209ddc5..ffcf7b3 100644
--- a/modules/std.io.html
+++ b/modules/std.io.html
@@ -37,7 +37,7 @@
All global variables must be 'declared' through a regular
assignment (even assigning nil will do) in a top-level
diff --git a/modules/std.string.html b/modules/std.string.html
index 2ca18f6..209f71c 100644
--- a/modules/std.string.html
+++ b/modules/std.string.html
@@ -33,11 +33,12 @@
- Concatenate arguments into a list.
+ Transpose a list of lists.
+ This function in Lua is equivalent to zip and unzip in more strongly
+ typed languages.
p
- function
- predicate function, of one argument returning a boolean
+
...
+ tuple of lists
@@ -467,7 +512,8 @@
Returns:
std.list
- new list containing elements e of l for which p (e) is true
+ new list containing
+ {self[1], ..., self[#self], l_1[1], ..., l_1[#l_1], ..., l_n[1], ..., l_n[#l_n]}
@@ -475,17 +521,16 @@
Return a sub-range of a list.
- (The equivalent of string.sub -- on strings; negative list indices
+ (The equivalent of string.sub on strings; negative list indices
count from the end of the list.)
Return a shallow copy of non-private object fields.
+
+
-
Methods
-
+
Tables
-
- std.object.__call
-
-
- Return a clone of object.
-
-
Normally a cloned object will share its metatable with its prototype,
- unless some new fields for the cloned object begin with '_', in which
- case they are merged into a copy of the prototype metatable to form
- a new metatable for the cloned object (and its clones).
-
-
- Return a shallow copy of non-private object fields.
-
-
This pseudo-metamethod is used during object cloning to make the
- intial new object table, and can be overridden in other objects
- for greater control of which fields are considered non-private.
-
-
-
-
-
This function doesn't recurse explicity, but relies upon suitable
- __tostring metamethods in contained objects.
+ __tostring metamethods in contained objects.
Returns:
@@ -388,6 +336,77 @@
Returns:
+
+
+
Metamethods
+
+
+
+ std.object:__call (...)
+
+
+ Return a clone of object.
+
+
Normally a cloned object will share its metatable with its prototype,
+ unless some new fields for the cloned object begin with '_', in which
+ case they are merged into a copy of the prototype metatable to form
+ a new metatable for the cloned object (and its clones).
+
+
Parameters:
+
+
...
+ arguments for _init
+
+
+
+
Returns:
+
+
+ std.object
+ a clone of the called object.
+
+
+
+
+
+
+
+
+ std.object:__tostring ()
+
+
+ Return a string representation of object.
+
+
+
+
+
+ Return a shallow copy of non-private object fields.
+
+
This pseudo-metamethod is used during object cloning to make the
+ intial new object table, and can be overridden in other objects
+ for greater control of which fields are considered non-private.
+
+
+
+
+
Simple getopt wrapper.
- If the caller didn't supply their own already, -- adds --version/-V
+ If the caller didn't supply their own already, adds --version/-V
and --help/-h options automatically;
stops program if there was an error, or if --help or --version was
used.
diff --git a/modules/std.html b/modules/std.html
index d0ae349..a5b9dea 100644
--- a/modules/std.html
+++ b/modules/std.html
@@ -40,16 +40,16 @@
A container is a std.object with no methods. It's functionality is
+ instead defined by its metamethods.
+
+
Where an Object uses the __index metatable entry to hold object
+ methods, a Container stores its contents using __index, preventing
+ it from having methods in there too.
+
+
Although there are no actual methods, Containers are free to use
+ metamethods (__index, __sub, etc) and, like Objects, can supply
+ module functions by listing them in _functions. Also, since a
+ std.container is a std.object, it can be passed to the
+ std.object module functions, or anywhere else a std.object is
+ expected.
+
+
Container derived objects returned directly from a require statement
+ may also provide module functions, which can be called only from the
+ initial prototype object returned by require , but are not passed
+ on to derived objects during cloning:
+
+
> Container = require "std.container"
+ > x = Container {}
+ > = Container.prototype (x)
+ Object
+ > = x.prototype (o)
+ stdin:1: attempt to call field 'prototype' (a nil value)
+ ...
+
+
+
To add functions like this to your own prototype objects, pass a table
+ of the module functions in the _functions private field before
+ cloning, and those functions will not be inherited by clones.
+
+
> Container = require "std.container"
+ > Graph = Container {
+ >> _type = "Graph",
+ >> _functions = {
+ >> nodes = function (graph)
+ >> local n = 0
+ >> for _ in pairs (graph) do n = n + 1 end
+ >> return n
+ >> end,
+ >> },
+ >> }
+ > g = Graph { "node1", "node2" }
+ > = Graph.nodes (g)
+ 2
+ > = g.nodes
+ nil
+
+
+
When making your own prototypes, start from std.container if you
+ want to access the contents of your objects with the [] operator, or
+ std.object if you want to access the functionality of your objects
+ with named object methods.
This module creates the root prototype object from which every other
object is descended. There are no classes as such, rather new objects
- are created by cloning an existing prototype object, and then changing
- or adding to it. Further objects can then be made by cloning the changed
+ are created by cloning an existing object, and then changing or adding
+ to the clone. Further objects can then be made by cloning the changed
object, and so on.
-
Objects are cloned by simply calling an existing object which then
- serves as a prototype, from which the new object is copied.
+
Objects are cloned by simply calling an existing object, which then
+ serves as a prototype from which the new object is copied.
All valid objects contain a field _init, which determines the syntax
required to execute the cloning process:
_init can be a list of keys; then the unnamed init_1 through
- init_n values from the argument table are assigned to the
+ init_m values from the argument table are assigned to the
corresponding keys in new_object;
Or it can be a function, in which the arguments passed to the
prototype during cloning are simply handed to the _init function:
-
new_object = prototype (value, ...)
+
new_object = proto_object (arg, ...)
-
Field names beginning with "_" are private, and moved into the object
- metatable during cloning. Unless new_object changes the metatable this
- way, then it will share a metatable with prototype for efficiency.
-
Objects, then, are essentially tables of field_n = value_n pairs:
-
-
Access an object field: object.field
-
Call an object method: object:method (...)
-
Call a "class" method: Class.method (object, ...)
-
Add a field: object.field = x
-
Add a method: function object:method (...) ... end
Normally new_object automatically shares a metatable with
+ proto_object. However, field names beginning with "_" are private,
+ and moved into the object metatable during cloning. So, adding new
+ private fields to an object during cloning will result in a new
+ metatable for new_object that also contains a copy of all the entries
+ in the proto_object metatable.
-
+
Note that Object methods are stored in the __index field of their
+ metatable, and so cannot also use __index to lookup references with
+ square brackets. See std.container objects if you want to do that.
Changing the values of these fields in a new object will change the
+ corresponding behaviour.
-
This can't and shouldn't be set directly, because the Object class
- manages it transparently during cloning.
Fields:
-
_type
- string
- derived objects can override this for objects
- intended to be a prototype for further specialised objects.
-
_inittable or function
- Derived objects can override this to be
- a set of keys to use for assigning unnamed arguments, or a function
- to that will be called with unnamed arguments durict cloning.
+ a table of field names, or
+ initialisation function, used by clone
+
+
_functions
+ nil or table
+ a table of module functions not copied
+ by std.object.__call
+
+
_type
+ string
+ type of Object, returned by prototype
+ (default "Object")
- Return a stringified version of the contents of object.
+ Return a string representation of this object.
-
First the object type, and then between { and } a list of the array
- part of the object table (without numeric keys) followed by the
- remaining key-value pairs.
+
First the object type, and then between { and } a list of the
+ array part of the object table (without numeric keys) followed
+ by the remaining key-value pairs.
This function doesn't recurse explicity, but relies upon suitable
- __tostring metamethods in contained objects.
+ __tostring metamethods in field values.
+
- Return a new table with a shallow copy of all non-private fields
- in object, where private fields have keys prefixed with "_".
-
-
Parameters:
-
-
self
+ Return a shallow copy of non-private object fields.
+
Used by clone to get the base contents of the new object. Can
+ be overridden in other objects for greater control of which fields
+ are considered non-private.
-
-
Returns:
table
- raw (non-object) table of object fields
+ a shallow copy of non-private object fields
-
-
-
-
-
- std.object:type (o)
-
-
-
-
Return the extended object type, if any, else primitive type.
-
-
It's conventional to organise similar objects according to a string
- valued _type field, which can then be queried using this function.
- Return a clone of object.
+ Clone this Object.
-
Normally a cloned object will share its metatable with its prototype,
- unless some new fields for the cloned object begin with '_', in which
- case they are merged into a copy of the prototype metatable to form
- a new metatable for the cloned object (and its clones).
- Return a shallow copy of non-private object fields.
+ __index = {
+ push = function (self) ... end,
+ pop = function (self) ... end,
+ },
+ }
+ stack = Stack {}
-
This pseudo-metamethod is used during object cloning to make the
- intial new object table, and can be overridden in other objects
- for greater control of which fields are considered non-private.
+ stack:prototype () --> "Stack"
+
-
Derived from std.container, and inherits Container's metamethods.
-
+
Note that Functions listed below are available only available from the
+ Set prototype returned by requiring this module, because Container
+ objects cannot have object methods.
Derived from std.container, and inherits Container's metamethods.
+
+
Note that Functions listed below are only available from the Tree
+ prototype return by requiring this module, because Container objects
+ cannot have object methods.
The returned iterator function performs a depth-first traversal of
+ tr, and at each node it returns {node-type, tree-path, tree-node}
+ where node-type is branch, join or leaf; tree-path is a
+ list of keys used to reach this node, and tree-node is the current
+ node.
Note that the tree-path reuses the same table on each iteration, so
+ you must table.clone a copy if you want to take a snap-shot of the
+ current state of the tree-path list before the next iteration
+ changes it.
+
+
+
Parameters:
+
+
tr
+ tree or table
+ tree or tree-like table to iterate over
+
local OptionParser = require "std.optparse"
+ local parser = OptionParser (spec)
+ _G.arg, opts = parser:parse (_G.arg)
+
+
+
The string spec passed to OptionParser must be a specially formatted
+ help text, of the form:
+
+
any text VERSION
+ Additional lines of text to show when the --version
+ option is passed.
+
+ Several lines or paragraphs are permitted.
+
+ Usage: PROGNAME
+
+ Banner text.
+
+ Optional long description text to show when the --help
+ option is passed.
+
+ Several lines or paragraphs of long description are permitted.
+
+ Options:
+
+ -h, --help display this help, then exit
+ --version display version information, then exit
+ -b a short option with no long option
+ --long a long option with no short option
+ --another-long a long option with internal hypen
+ --true a Lua keyword as an option name
+ -v, --verbose a combined short and long option
+ -n, --dryrun, --dry-run several spellings of the same option
+ -u, --name=USER require an argument
+ -o, --output=[FILE] accept an optional argument
+ -- end of options
+
+Footer text. Several lines or paragraphs are permitted.
+
+Please report bugs at bug-list@yourhost.com
+
+
+
Most often, everything else is handled automatically. After calling
+ parser:parse as shown above, _G.arg will contain unparsed arguments,
+ usually filenames or similar, and opts will be a table of parsed
+ option values. The keys to the table are the long-options with leading
+ hyphens stripped, and non-word characters turned to _. For example
+ if --another-long had been found in _G.arg then opts would
+ have a key named another_long. If there is no long option name, then
+ the short option is used, e.g. opts.b will be set. The values saved
+ in those keys are controlled by the option handler, usually just true
+ or the option argument string as appropriate.
+
+
On those occasions where more complex processing is required, handlers
+ can be replaced or added using parser:on.
+ Instantiate a new parser.
+ Read the documented options from spec and return a new parser that
+ can be passed to parse for parsing those options from an argument
+ list.
+
+
+
stop_at_nonopt
- if true, stop option processing at first non-option
-
-
-
-
Returns:
-
-
- table of remaining non-options
-
- table of option key-value list pairs
-
- table of error messages
-
-
-
-
-
-
-
-
- processargs (prog, ...)
-
-
- Simple getopt wrapper.
- If the caller didn't supply their own already, adds --version/-V
- and --help/-h options automatically;
- stops program if there was an error, or if --help or --version was
- used.
-
-
-
Module table.
+ Lazy load submodules into std on first reference. On initial
+ load, std has the usual single version entry, but the __index
+ metatable will automatically require submodules on first reference:
+
+
local std = require "std"
+ local prototype = std.container.prototype
+
+
Fields:
@@ -709,6 +726,38 @@
Fields:
+
+
+
Metamethods
+
+
+
+
+ __index (name)
+
+
+ Lazy loading of stdlib modules.
+ Don't load everything on initial startup, wait until first attempt
+ to access a submodule, and then load it on demand.
+
+
+
...they can also be called as module functions with an explicit argument:
+
... some can also be called as module functions with an explicit list
+ argument in the first or last parameter, check the documentation for
+ details:
local List = require "std.list"
local l = List {1, 2, 3}
@@ -98,27 +101,95 @@
+
+
+ List
+ new list containing {l[#l], ..., l[1]}
+
+
+
+
+
+
+
+
+ std.list.shape (s, l)
+
+
+ Shape a list according to a list of dimensions.
+
+
Dimensions are given outermost first and items from the original
+ list are distributed breadth first; there may be one 0 indicating
+ an indefinite number. Hence, {0} is a flat list,
+ {1} is a singleton, {2, 0} is a list of
+ two lists, and {0, 2} is a list of pairs.
+
+
Algorithm: turn shape into all positive numbers, calculating
+ the zero if necessary and making sure there is at most one;
+ recursively walk the shape, adding empty tables until the bottom
+ level is reached at which point add table items instead, using a
+ counter to walk the flattened original list.
+
+
+
Parameters:
+
+
stable
- list of tables {i1=t1, ..., in=tn}
+ {d1, ..., dn}
- Map a function over a list of lists.
+ Return a sub-range of a list.
+ (The equivalent of string.sub on strings; negative list indices
+ count from the end of the list.)
p
- function
+ func
predicate function, of one argument returning a boolean
@@ -735,35 +1398,32 @@
Parameters:
Returns:
- std.list
- new list containing elements e of self for which p (e) is true
+ List
+ new list containing elements e of self for which
+ p (e) is true
+
- std.list
+ Listn copies of self appended together
@@ -944,25 +1614,17 @@
Returns:
- std.list:reverse (self)
+ std.list:reverse ()
Reverse a list.
-
Parameters:
-
-
self
-
-
-
-
-
Returns:
- std.list
+ List
new list containing {self[#self], ..., self[1]}
@@ -975,19 +1637,7 @@
Returns:
std.list:shape (s)
- Shape a list according to a list of dimensions.
-
-
Dimensions are given outermost first and items from the original
- list are distributed breadth first; there may be one 0 indicating
- an indefinite number. Hence, {0} is a flat list,
- {1} is a singleton, {2, 0} is a list of
- two lists, and {0, 2} is a list of pairs.
-
-
Algorithm: turn shape into all positive numbers, calculating
- the zero if necessary and making sure there is at most one;
- recursively walk the shape, adding empty tables until the bottom
- level is reached at which point add table items instead, using a
- counter to walk the flattened original list.
+ Shape a list according to a list of dimensions.
Container derived objects returned directly from a require statement
+
Container derived objects returned directly from a require statement
may also provide module functions, which can be called only from the
- initial prototype object returned by require , but are not passed
+ initial prototype object returned by require , but are not passed
on to derived objects during cloning:
Return a sub-range of a list.
- (The equivalent of string.sub on strings; negative list indices
+ (The equivalent of string.sub on strings; negative list indices
count from the end of the list.)
@@ -1035,7 +1035,7 @@
Return a sub-range of a list.
- (The equivalent of string.sub on strings; negative list indices
+ (The equivalent of string.sub on strings; negative list indices
count from the end of the list.)
@@ -1721,7 +1721,7 @@
+ Return obj with references to the fields of src merged in.
+
+
More importantly, split the fields in src between obj and its
+ metatable. If any field names begin with _, attach a metatable
+ to obj if it doesn't have one yet, and copy the "private" _
+ prefixed fields there.
+
+
You might want to use this function to instantiate your derived
+ objct clones when the prototype's _init is a function -- when
+ _init is a table, the default (inherited unless you overwrite
+ it) clone method calls mapfields automatically. When you're
+ using a function _init setting, clone doesn't know what to
+ copy into a new object from the _init function's arguments...
+ so you're on your own. Except that calling mapfields inside
+ _init is safer than manually splitting src into obj and
+ its metatable, because you'll pick up fixes and changes when you
+ upgrade stdlib.
+
+
+
+
+
+ table
+ obj with non-private fields from src merged,
+ and a metatable with private fields (if any) merged, both sets
+ of keys renamed according to map
+
+
+
+
+
local OptionParser = require "std.optparse"
- local parser = OptionParser (spec)
- _G.arg, opts = parser:parse (_G.arg)
-
-
-
The string spec passed to OptionParser must be a specially formatted
- help text, of the form:
-
any text VERSION
+ local parser = OptionParser [[
+ any text VERSION
Additional lines of text to show when the --version
option is passed.
@@ -95,36 +90,56 @@
Class std.optparse
Options:
- -h, --help display this help, then exit
- --version display version information, then exit
-b a short option with no long option
--long a long option with no short option
--another-long a long option with internal hypen
- --true a Lua keyword as an option name
-v, --verbose a combined short and long option
-n, --dryrun, --dry-run several spellings of the same option
-u, --name=USER require an argument
-o, --output=[FILE] accept an optional argument
- -- end of options
+ --version display version information, then exit
+ --help display this help, then exit
Footer text. Several lines or paragraphs are permitted.
Please report bugs at bug-list@yourhost.com
+]]
+
+_G.arg, _G.opts = parser:parse (_G.arg)
Most often, everything else is handled automatically. After calling
parser:parse as shown above, _G.arg will contain unparsed arguments,
- usually filenames or similar, and opts will be a table of parsed
+ usually filenames or similar, and _G.opts will be a table of parsed
option values. The keys to the table are the long-options with leading
hyphens stripped, and non-word characters turned to _. For example
- if --another-long had been found in _G.arg then opts would
+ if --another-long had been found in _G.arg then _G.opts would
have a key named another_long. If there is no long option name, then
- the short option is used, e.g. opts.b will be set. The values saved
- in those keys are controlled by the option handler, usually just true
- or the option argument string as appropriate.
+ the short option is used, e.g. _G.opts.b will be set. The values
+ saved in those keys are controlled by the option handler, usually just
+ true or the option argument string as appropriate.
On those occasions where more complex processing is required, handlers
- can be replaced or added using parser:on.
+ can be replaced or added using parser:on. A good option to always
+ add, is to make -- signal the end of processed options, so that any
+ options following -- on the command line, even if they begin with a
+ hyphen and look like options otherwise, are not processed but instead
+ left in the modified _G.arg returned by parser:parse:
+
+
parser:on ('--', parser.finished)
+
+
+
See the documentation for std.optparse:on for more details of how to
+ use this powerful method.
+
+
When writing your own handlers for std.optparse:on, you only need
+ to deal with normalised arguments, because combined short arguments
+ (-xyz), equals separators to long options (--long=ARG) are fully
+ expanded before any handler is called.
+
+
Note that std.io.die and std.io.warn will only prefix messages
+ with parser.program if the parser options are assigned back to
+ _G.opts as shown in the example above.
Instantiate a new parser.
Read the documented options from spec and return a new parser that
can be passed to parse for parsing those options from an argument
- list.
+ list. Options are recognised as lines that begin with at least two
+ spaces, followed by a hyphen.
Return a Lua boolean equivalent of various optarg strings.
- Report an option parse error if optarg is not recognised.
+ Report an option parse error if optarg is not recognised.
+
+
Pass this as the value function to on when you want various
+ truthy or falsey option arguments to be coerced to a Lua true
+ or false respectively in the options table.
- Finish option processing
- Usually indicated by -- at arglist[i].
+ Finish option processing
+
+
This is the handler automatically assigned to the option written as
+ -- in the OptionParser spec argument. You can also pass it as
+ the handler argument to on if you want to manually add an end
+ of options marker without writing it in the OptionParser spec.
+
+
This handler tells the parser to stop processing arguments, so that
+ anything after it will be an argument even if it otherwise looks
+ like an option.
- Option at arglist[i] is a boolean switch.
+ Option at arglist[i] is a boolean switch.
+
+
This is the handler automatically assigned to options that have
+ --long-opt or -x style specifications in the OptionParser spec
+ argument. You can also pass it as the handler argument to on for
+ options you want to add manually without putting them in the
+ OptionParser spec.
+
+
Beware that, unlikerequired, this handler will store multiple
+ occurrences of a command-line option as a table only when given a
+ value function. Automatically assigned handlers do not do this, so
+ the option will simply be true if the option was given one or more
+ times on the command-line.
- Normalise an argument list.
- Separate short options, remove = separators from
- --long-option=optarg etc.
+ Report an option parse error, then exit with status 2.
+
+
Use this in your custom option handlers for consistency with the
+ error output from built-in optparse error messages.
Parameters:
-
arglist
- table
- list of arguments to normalise
+
- Add an option handler.
+ Option at arglist[i] can take an argument.
+ Argument is accepted only if there is a following entry that does not
+ begin with a '-'.
+
+
This is the handler automatically assigned to options that have
+ --opt=[ARG] style specifications in the OptionParser spec
+ argument. You can also pass it as the handler argument to on for
+ options you want to add manually without putting them in the
+ OptionParser spec.
+
+
Like required, this handler will store multiple occurrences of a
+ command-line option.
Parameters:
-
name
- opts
- of the option, or list of option names
+
handler
- on_handler
- function to call when any of opts is
- encountered
+
i
+ int
+ index of last processed element of arglist
value
- additional value passed to on_handler
+ either a function to process the option
+ argument, or a default value if encountered without an optarg
+ (default true)
+
Returns:
+
+
+ int
+ index of next element of arglist to process
+
- Function signature of an option handler for on.
+
+
Option at arglist[i} requires an argument.
+
+
This is the handler automatically assigned to options that have
+ --opt=ARG style specifications in the OptionParser spec argument.
+ You can also pass it as the handler argument to on for options
+ you want to add manually without putting them in the OptionParser
+ spec.
+
+
Normally the value stored in the opt table by this handler will be
+ the string given as the argument to that option on the command line.
+ However, if the option is given on the command-line multiple times,
+ opt["name"] will end up with all those arguments stored in the
+ array part of a table:
value
- additional value registered with on
- (default nil)
+ either a function to process the option argument,
+ or a forced value to replace the user's option argument.
- Option at arglist[i] can take an argument.
- Argument is accepted only if there is a following entry that does not
- begin with a '-'.
+ Map various option strings to equivalent Lua boolean values.
-
i
- int
- index of last processed element of arglist
+
0
+ false
-
value
- either a function to process the option
- argument, or a default value if encountered without an optarg
- (default true)
+
no
+ false
+
+
n
+ false
+
+
true
+ true
+
+
1
+ true
+
+
yes
+ true
+
+
y
+ true
-
Returns:
-
- int
- index of next element of arglist to process
-
+
+
+
+
+
+
+ std.optparse.opts
+
+
+ Parsed options table, with a key for each encountered option, each
+ with value set by that option's on_handler. Where an option
+ has one or more long-options specified, the key will be the first
+ one of those with leading hyphens stripped and non-alphanumeric
+ characters replaced with underscores. For options that can only be
+ specified by a short option, the key will be the letter of the first
+ of the specified short options:
+
+
Generally there will be one key for each previously specified
+ option (either automatically assigned by OptionParser or
+ added manually with on) containing the value(s) assigned by the
+ associated on_handler. For automatically assigned handlers,
+ that means true for straight-forward flags and
+ optional-argument options for which no argument was given; or else
+ the string value of the argument passed with an option given only
+ once; or a table of string values of the same for arguments given
+ multiple times.
If you write your own handlers, or otherwise specify custom
+ handling of options with on, then whatever value those handlers
+ return will be assigned to the respective keys in opts .
+
+
+
- Parse arglist.
+ Customized parser for your options.
+
This table is returned by OptionParser, and most importantly has
+ the parse method you call to fill the opts table according to
+ what command-line options were passed to your program.
-
When the automatically assigned option handlers don't do everything
+ you require, or when you don't want to put an option into the
+ OptionParserspec argument, use this function to specify custom
+ behaviour. If you write the option into the spec argument anyway,
+ calling this function will replace the automatically assigned handler
+ with your own.
name
+ opts
+ of the option, or list of option names
-
i
- int
- index of last processed element of arglist
+
handler
+ on_handler
+ function to call when any of opts is
+ encountered
value
- either a function to process the option argument,
- or a forced value to replace the user's option argument.
+ additional value passed to on_handler
-
Returns:
-
-
- int
- index of next element of arglist to process
-
- Give warning with the name of program and file (if any).
+
+
Give warning with the name of program and file (if any).
+ If there is a global prog table, prefix the message with
+ prog.name or prog.file, and prog.line if any. Otherwise
+ if there is a global opts table, prefix the message with
+ opts.program and opts.line if any. std.optparse:parse
+ returns an opts table that provides the required program
+ field, as long as you assign it back to _G.opts:
+
+
local OptionParser = require "std.optparse"
+ local parser = OptionParser "eg 0\nUsage: eg\n"
+ _G.arg, _G.opts = parser:parse (_G.arg)
+ if not _G.opts.keep_going then
+ require "std.io".warn "oh noes!"
+ end
+
Split a string at a given separator.
+ Separator is a Lua pattern, so you have to escape active characters,
+ ^$()%.[]*+-? with a % prefix to match a literal character in s .
Derived from std.container, and inherits Container's metamethods.
-
Note that Functions listed below are available only available from the
- Set prototype returned by requiring this module, because Container
+
Note that Functions listed below are only available from the Set
+ prototype returned by requiring this module, because Container
objects cannot have object methods.
p1
+ table
+ =a1, ..., pn=an} table of parameters to bind to given arguments
Returns:
- function with ai already bound
+ function with pi already bound
+
+
+
+
+
+
+
+
+ case (with, branches)
+
+
+
+
A rudimentary case statement.
+ Match with against keys in branches table, and return the result
+ of running the function in the table value for the matching key, or
+ the first non-key value function if no key matches.
+
+
return case (type (object), {
+ table = function () return something end,
+ string = function () return something else end,
+ function (s) error ("unhandled type: "..s) end,
+ })
+
+
+
+
+
+
Parameters:
+
+
with
+ expression to match
+
+
branches
+ table
+ map possible matches to functions
+
+
+
+
Returns:
+
+
+ the return value from function with a matching key, or nil.
@@ -197,7 +244,14 @@
Returns:
Returns:
- composition of f1 ... fn
+ composition of fn (... (f1) ...): note that this is the reverse
+ of what you might expect, but means that code like:
+
+
functional.compose (function (x) return f (x) end,
+ function (x) return g (x) end))
+
+ Look for a path segment match of patt in pathstrings.
+
+
+
Parameters:
+
+
pathstrings
+ string
+ pathsep delimited path elements
+
+
patt
+ string
+ a Lua pattern to search for in pathstrings
+
+
init
+ int
+ element (not byte index!) to start search at.
+ Negative numbers begin counting backwards from the last element
+ (default 1)
+
+
plain
+ bool
+ unless false, treat patt as a plain
+ string, not a pattern. Note that if plain is given, then init
+ must be given as well.
+ (default false)
+
+
+
+
Returns:
+
+
+ the matching element number (not byte index!) and full text
+ of the matching element, if any; otherwise nil
+
+
+
+
+
+
+
+
+ insert (pathstrings[, pos=n+1], value)
+
+
+ Insert a new element into a package.path like string of paths.
+
+
+
Parameters:
+
+
pathstrings
+ string
+ a package.path like string
+
+
pos
+ int
+ element index at which to insert value, where n is
+ the number of elements prior to insertion
+ (default n+1)
+
+
+
+ string
+ a new string with the new element inserted
+
+
+
+
+
+
+
+
+ mappath (pathstrings, callback, ...)
+
+
+ Call a function with each element of a path string.
+
+
+
Parameters:
+
+
pathstrings
+ string
+ a package.path like string
+
+
callback
+ mappath_callback
+ function to call for each element
+
+
...
+ additional arguments passed to callback
+
+
+
+
Returns:
+
+
+ nil, or first non-nil returned by callback
+
+
+
+
+
+
+
+
+ mappath_callback (element, ...)
+
+
+ Function signature of a callback for mappath.
+
+
+
Parameters:
+
+
element
+ string
+ an element from a pathsep delimited string of
+ paths
+
+
...
+ additional arguments propagated from mappath
+
+
+
+
Returns:
+
+
+ non-nil to break, otherwise continue with the next element
+
+
+
+
+
+
+
+
+ normalize (...)
+
+
+ Normalize a path list.
+ Removing redundant . and .. directories, and keep only the first
+ instance of duplicate elements. Each argument can contain any number
+ of pathsep delimited elements; wherein characters are subject to
+ / and ? normalization, converting / to dirsep and ? to
+ path_mark (unless immediately preceded by a % character).
+
+
+
Parameters:
+
+
...
+ path elements
+
+
+
+
Returns:
+
+
+ string
+ a single normalized pathsep delimited paths string
+
+
+
+
+
+
+
+
+ remove (pathstrings[, pos=n])
+
+
+ Remove any element from a package.path like string of paths.
+
+
+
Parameters:
+
+
pathstrings
+ string
+ a package.path like string
+
+
pos
+ int
+ element index from which to remove an item, where n
+ is the number of elements prior to removal
+ (default n)
+
+
+
+
Returns:
+
+
+ string
+ a new string with given element removed
+
+
+
+
+
+
If you require "std", the contents of this module are all available
+ in the std.string table.
+
+
However, this module also contains references to the Lua core string
+ table entries, so it's safe to load it like this:
+
+
local string = require "std.string"
+
+
+
Of course, if you do that you'll lose references to any core string
+ functions overwritten by std.string , so you might want to save any
+ that you want access to before you overwrite them.
+
+
If your code does not require "std" anywhere, then you'll also need
+ to manually overwrite string functions in the global namespace if you
+ want to use them from there:
+
+
local assert, tostring = string.assert, string.tostring
+
+
+
And finally, to use the string metatable improvements with all core
+ strings, you'll need to merge this module's metatable into the core
+ string metatable (again, require "std" does this automatically):
Split a string at a given separator.
Separator is a Lua pattern, so you have to escape active characters,
- ^$()%.[]*+-? with a % prefix to match a literal character in s .
+ ^$()%.[]*+-? with a % prefix to match a literal character in s.
- Memoize a function, by wrapping it in a functable.
+ Memoize a function, by wrapping it in a functable.
+
+
To ensure that memoize always returns the same object for the same
+ arguments, it passes arguments to normalize (std.string.tostring
+ by default). You may need a more sophisticated function if memoize
+ should handle complicated argument equivalencies.
Parameters:
@@ -438,6 +443,9 @@
Parameters:
fn
function that returns a single result
+
normalize
+ [opt] function to normalize arguments
+
Returns:
@@ -451,28 +459,25 @@
Returns:
-
- metamethod (x, n)
+
+ memoize_normalize (...)
- Return given metamethod, if any, or nil.
+ Signature of memoize normalize functions.
Parameters:
-
x
- object to get metamethod of
-
-
n
- name of metamethod to get
+
...
+ arguments
Returns:
- metamethod function or nil if no metamethod or not a
- function
+ string
+ normalized arguments
diff --git a/modules/std.html b/modules/std.html
index 9f51b5f..e3dac79 100644
--- a/modules/std.html
+++ b/modules/std.html
@@ -3,7 +3,7 @@
- stdlib 39 Reference
+ stdlib 40 Reference
@@ -66,130 +66,35 @@
Classes
Module std
-
Global namespace scribbler.
-
For backwards compatibility with older releases, require "std"
- will inject the same functions into the global namespace as it
- has done previously, even though it is now deprecated.
+
Submodule lazy loader.
+
After requiring this module, simply referencing symbols in the submodule
+ hierarchy will load the necessary modules on demand.
-
For new code, much better than scribbling all over the global
- namespace, it's more hygienic to explicitly assign the results of
- requiring just the submodules you actually use to a local variable,
- and access its functions via that table.
+
Clients of older releases might be surprised by this new-found hygiene,
+ expecting the various changes that used to be automatically installed as
+ global symbols, or monkey patched into the core module tables and
+ metatables. Sometimes, it's still convenient to do that... when using
+ stdlib from the REPL, or in a prototype where you want to throw caution
+ to the wind and compatibility with other modules be damned, for example.
+ In that case, you can give stdlib permission to scribble all over your
+ namespaces with:
Module table.
- Lazy load submodules into std on first reference. On initial
+
Module table.
+
+
Lazy load submodules into std on first reference. On initial
load, std has the usual single version entry, but the __index
metatable will automatically require submodules on first reference:
Container derived objects returned directly from a require statement
- may also provide module functions, which can be called only from the
- initial prototype object returned by require , but are not passed
- on to derived objects during cloning:
-
-
> Container = require "std.container"
- > x = Container {}
- > = Container.prototype (x)
- Object
- > = x.prototype (o)
- stdin:1: attempt to call field 'prototype' (a nil value)
- ...
-
-
-
To add functions like this to your own prototype objects, pass a table
- of the module functions in the _functions private field before
- cloning, and those functions will not be inherited by clones.
-
-
> Container = require "std.container"
- > Graph = Container {
- >> _type = "Graph",
- >> _functions = {
- >> nodes = function (graph)
- >> local n = 0
- >> for _ in pairs (graph) do n = n + 1 end
- >> return n
- >> end,
- >> },
- >> }
- > g = Graph { "node1", "node2" }
- > = Graph.nodes (g)
- 2
- > = g.nodes
- nil
-
-
-
When making your own prototypes, start from std.container if you
- want to access the contents of your objects with the [] operator, or
- std.object if you want to access the functionality of your objects
- with named object methods.
When making your own prototypes, derive from std.container if you want
+ to access the contents of your objects with the [] operator, or from
+ std.object if you want to access the functionality of your objects with
+ named object methods.
Every list is also an object, and thus inherits all of the std.object
- methods, particularly use of object cloning for making new list objects.
+
Prototype Chain
-
In addition to calling methods on list objects in OO style...
-
local List = require "std.list"
- local l = List {1, 2, 3}
- for e in l:relems () do print (e) end
- => 3
- => 2
- => 1
-
-
-
... some can also be called as module functions with an explicit list
- argument in the first or last parameter, check the documentation for
- details:
-
-
local List = require "std.list"
- local l = List {1, 2, 3}
- for e in List.relems (l) do print (e) end
- => 3
- => 2
- => 1
-
List
- new list containing {l[1], ..., l[#l], x}
+ new list with x appended
+
Usage:
+
+
longer = append (short, "last")
+
@@ -337,12 +205,7 @@
Returns:
std.list.compare (l, m)
-
-
Compare two lists element-by-element, from left-to-right.
-
-
if a_list:compare (another_list) == 0 then print "same" end
-
-
+ Compare two lists element-by-element, from left-to-right.
Parameters:
@@ -352,20 +215,24 @@
Parameters:
a list
m
- table
- another list
+ List or table
+ another list, or table
Returns:
- -1 if l is less than m, 0 if they are the same, and 1
- if l is greater than m
+ -1 if l is less than m, 0 if they are the same, and 1
+ if l is greater than m
+
Usage:
+
+
if a_list:compare (another_list) == 0thenprint"same"end
+
@@ -373,7 +240,7 @@
Returns:
std.list.concat (l, ...)
- Concatenate arguments into a list.
+ Concatenate the elements from any number of lists.
Parameters:
@@ -391,12 +258,17 @@
Returns:
List
- new list containing
- {l[1], ..., l[#l], l_1[1], ..., l_1[#l_1], ..., l_n[1], ..., l_n[#l_n]}
+ new list with elements from arguments
+
- Filter a list according to a predicate.
+ Return a sub-range of a list.
+ (The equivalent of ??? on strings; negative list indices
+ count from the end of the list.)
Parameters:
-
p
- func
- predicate function, of one argument returning a boolean
-
-
-
- List
- new list containing {l[#l], ..., l[1]}
-
-
-
-
-
-
-
-
- std.list.shape (s, l)
-
-
- Shape a list according to a list of dimensions.
-
-
Dimensions are given outermost first and items from the original
- list are distributed breadth first; there may be one 0 indicating
- an indefinite number. Hence, {0} is a flat list,
- {1} is a singleton, {2, 0} is a list of
- two lists, and {0, 2} is a list of pairs.
-
-
Algorithm: turn shape into all positive numbers, calculating
- the zero if necessary and making sure there is at most one;
- recursively walk the shape, adding empty tables until the bottom
- level is reached at which point add table items instead, using a
- counter to walk the flattened original list.
-
-
-
This module creates the root prototype object from which every other
object is descended. There are no classes as such, rather new objects
are created by cloning an existing object, and then changing or adding
@@ -76,89 +80,56 @@
Class std.object
Objects are cloned by simply calling an existing object, which then
serves as a prototype from which the new object is copied.
-
All valid objects contain a field _init, which determines the syntax
- required to execute the cloning process:
+
Note that Object methods are stored in the __index field of their
+ metatable, and so cannot also use __index to lookup references with
+ square brackets. See std.container objects if you want to do that.
-
-
_init can be a list of keys; then the unnamed init_1 through
- init_m values from the argument table are assigned to the
- corresponding keys in new_object;
Normally new_object automatically shares a metatable with
- proto_object. However, field names beginning with "_" are private,
- and moved into the object metatable during cloning. So, adding new
- private fields to an object during cloning will result in a new
- metatable for new_object that also contains a copy of all the entries
- in the proto_object metatable.
+
+table
+ `-> Object
+
-
Note that Object methods are stored in the __index field of their
- metatable, and so cannot also use __index to lookup references with
- square brackets. See std.container objects if you want to do that.
_init
- table or function
- a table of field names, or
- initialisation function, used by clone
+ table or function
+ object initialisation
+ (default {})
_functions
- nil or table
- a table of module functions not copied
- by std.object.__call
+ table
+ module functions omitted when cloned
_type
- string
- type of Object, returned by prototype
+ string
+ object name
(default "Object")
+ -- `_init` can be a list of keys; then the unnamed `init_1` through
+-- `init_m` values from the argument table are assigned to the
+-- corresponding keys in `new_object`.
+local Process = Object {
+ _type = "Process",
+ _init = { "status", "out", "err" },
+ }
+ local process = Process {
+ procs[pid].status, procs[pid].out, procs[pid].err, -- auto assigned
+ command = pipeline[pid], -- manual assignment
+ }
+
+ -- Or it can be a function, in which the arguments passed to the
+-- prototype during cloning are simply handed to the `_init` function.
+local Bag = Object {
+ _type = "Bag",
+ _init = function (obj, ...)
+ for e in std.elems {...} do
+ obj[#obj + 1] = e
+ end
+ return obj
+ end,
+ }
+ local bag = Bag ("function", "arguments", "sent", "to", "_init")
- Return a clone of this object, and its metatable.
+ Clone an Object.
-
Private fields are stored in the metatable.
+
Objects are essentially tables of field_n = value_n pairs.
+
+
Normally new_object automatically shares a metatable with
+ proto_object. However, field names beginning with "_" are private,
+ and moved into the object metatable during cloning. So, adding new
+ private fields to an object during cloning will result in a new
+ metatable for new_object that also happens to contain a copy of all
+ the entries from the proto_object metatable.
+
+
While clones of Object inherit all properties of their prototype,
+ it's idiomatic to always keep separate tables for the module table and
+ the root object itself: That way you can't mistakenly engage the slower
+ clone-from-module-table process unnecessarily.
- Return a string representation of this object.
+ Return obj with references to the fields of src merged in.
-
First the object type, and then between { and } a list of the
- array part of the object table (without numeric keys) followed
- by the remaining key-value pairs.
+
More importantly, split the fields in src between obj and its
+ metatable. If any field names begin with "_", attach a metatable
+ to obj by cloning the metatable from src, and then copy the
+ "private" _ prefixed fields there.
-
This function doesn't recurse explicity, but relies upon suitable
- __tostring metamethods in field values.
+
You might want to use this function to instantiate your derived
+ object clones when the src._init is a function -- when
+ src._init is a table, the default (inherited unless you overwrite
+ it) clone method calls mapfields automatically. When you're
+ using a function _init setting, clone doesn't know what to
+ copy into a new object from the _init function's arguments...
+ so you're on your own. Except that calling mapfields inside
+ _init is safer than manually splitting src into obj and
+ its metatable, because you'll pick up any fixes and changes when
+ you upgrade stdlib.
+
- string
- stringified container representation
+ table
+ obj with non-private fields from src merged,
+ and a metatable with private fields (if any) merged, both sets
+ of keys renamed according to map
-
- Return a shallow copy of non-private object fields.
+ Type of an object, or primitive.
+
+
It's conventional to organise similar objects according to a
+ string valued _type field, which can then be queried using this
+ function.
-
Used by clone to get the base contents of the new object. Can
- be overridden in other objects for greater control of which fields
- are considered non-private.
+
Additionally, this function returns the results of ??? for
+ file objects, or type otherwise.
+
Parameters:
+
+
x
+ anything
+
+
Returns:
- table
- a shallow copy of non-private object fields
+ string
+ type of x
-
- Return obj with references to the fields of src merged in.
+ Return an in-order iterator over public object fields.
-
More importantly, split the fields in src between obj and its
- metatable. If any field names begin with _, attach a metatable
- to obj if it doesn't have one yet, and copy the "private" _
- prefixed fields there.
-
You might want to use this function to instantiate your derived
- objct clones when the prototype's _init is a function -- when
- _init is a table, the default (inherited unless you overwrite
- it) clone method calls mapfields automatically. When you're
- using a function _init setting, clone doesn't know what to
- copy into a new object from the _init function's arguments...
- so you're on your own. Except that calling mapfields inside
- _init is safer than manually splitting src into obj and
- its metatable, because you'll pick up fixes and changes when you
- upgrade stdlib.
-
-
-
-
- table
- obj with non-private fields from src merged,
- and a metatable with private fields (if any) merged, both sets
- of keys renamed according to map
+
First the object type, and then between { and } a list of the
+ array part of the object table (without numeric keys) followed
+ by the remaining key-value pairs.
+
This function doesn't recurse explicity, but relies upon suitable
+ __tostring metamethods in field values.
-
Parameters:
-
-
x
- anything
-
-
Returns:
- string
- type of x
+ string
+ stringified object representation
+
- local parser = OptionParser [[
- any text VERSION
- Additional lines of text to show when the --version
- option is passed.
-
- Several lines or paragraphs are permitted.
-
- Usage: PROGNAME
-
- Banner text.
-
- Optional long description text to show when the --help
- option is passed.
-
- Several lines or paragraphs of long description are permitted.
-
- Options:
-
- -b a short option with no long option
- --long a long option with no short option
- --another-long a long option with internal hypen
- -v, --verbose a combined short and long option
- -n, --dryrun, --dry-run several spellings of the same option
- -u, --name=USER require an argument
- -o, --output=[FILE] accept an optional argument
- --version display version information, then exit
- --help display this help, then exit
-
-Footer text. Several lines or paragraphs are permitted.
-
-Please report bugs at bug-list@yourhost.com
-]]
-
-_G.arg, _G.opts = parser:parse (_G.arg)
-
-
-
Most often, everything else is handled automatically. After calling
- parser:parse as shown above, _G.arg will contain unparsed arguments,
- usually filenames or similar, and _G.opts will be a table of parsed
- option values. The keys to the table are the long-options with leading
- hyphens stripped, and non-word characters turned to _. For example
- if --another-long had been found in _G.arg then _G.opts would
- have a key named another_long. If there is no long option name, then
- the short option is used, e.g. _G.opts.b will be set. The values
- saved in those keys are controlled by the option handler, usually just
- true or the option argument string as appropriate.
-
-
On those occasions where more complex processing is required, handlers
- can be replaced or added using parser:on. A good option to always
- add, is to make -- signal the end of processed options, so that any
- options following -- on the command line, even if they begin with a
- hyphen and look like options otherwise, are not processed but instead
- left in the modified _G.arg returned by parser:parse:
-
-
parser:on ('--', parser.finished)
-
-
-
See the documentation for std.optparse:on for more details of how to
- use this powerful method.
-
When writing your own handlers for std.optparse:on, you only need
- to deal with normalised arguments, because combined short arguments
- (-xyz), equals separators to long options (--long=ARG) are fully
- expanded before any handler is called.
-
-
Note that std.io.die and std.io.warn will only prefix messages
- with parser.program if the parser options are assigned back to
- _G.opts as shown in the example above.
- Instantiate a new parser.
- Read the documented options from spec and return a new parser that
- can be passed to parse for parsing those options from an argument
- list. Options are recognised as lines that begin with at least two
- spaces, followed by a hyphen.
+ OptionParser prototype object.
+
+
Most often, after instantiating an OptionParser, everything else
+ is handled automatically.
+
+
Then, calling parser:parse as shown below saves unparsed arguments
+ into _G.arg (usually filenames or similar), and _G.opts will be a
+ table of successfully parsed option values. The keys into this table
+ are the long-options with leading hyphens stripped, and non-word
+ characters turned to _. For example if --another-long had been
+ found in the initial _G.arg, then _G.opts will have a key named
+ another_long, with an appropriate value. If there is no long
+ option name, then the short option is used, i.e. _G.opts.b will be
+ set.
+
+
The values saved against those keys are controlled by the option
+ handler, usually just true or the option argument string as
+ appropriate.
+
+
+
program
+ string
+ the first word following "Usage:" from spec
+
+
version
+ string
+ the last white-space delimited word on the first line
+ of text from spec
+
+
versiontext
+ string
+ everything preceding "Usage:" from spec, and
+ which will be displayed by the versionon_handler
+
+
helptext
+ string
+ everything including and following "Usage:" from
+ spec string and which will be displayed by the help
+ on_handler
+
+
+
+
+
+
+
Usage:
+
+
+ local std = require"std"
+
+ local optparser = std.optparse [[
+ any text VERSION
+ Additional lines of text to show when the --version
+ option is passed.
+
+ Several lines or paragraphs are permitted.
+
+ Usage: PROGNAME
+
+ Banner text.
+
+ Optional long description text to show when the --help
+ option is passed.
+
+ Several lines or paragraphs of long description are permitted.
+
+ Options:
+
+ -b a short option with no long option
+ --long a long option with no short option
+ --another-long a long option with internal hypen
+ -v, --verbose a combined short and long option
+ -n, --dryrun, --dry-run several spellings of the same option
+ -u, --name=USER require an argument
+ -o, --output=[FILE] accept an optional argument
+ --version display version information, then exit
+ --help display this help, then exit
+
+ Footer text. Several lines or paragraphs are permitted.
+
+ Please report bugs at bug-list@yourhost.com
+ ]]
+
+ -- Note that std.io.die and std.io.warn will only prefix messages
+-- with `parser.program` if the parser options are assigned back to
+-- `_G.opts`:
+ _G.arg, _G.opts = optparser:parse (_G.arg)
+
+
+
+
+
Functions
+ Methods
+
+
+
+ std.optparse.OptionParser_Init (spec)
+
+
+ Signature for initialising a custom OptionParser.
+
+
Read the documented options from spec and return custom parser that
+ can be used for parsing the options described in spec from a run-time
+ argument list. Options in spec are recognised as lines that begin
+ with at least two spaces, followed by a hyphen.
- parser
- a parser for options described by spec
+ OptionParser
+ a parser for options described by spec
+
Usage:
+
+
customparser = std.optparse (optparse_spec)
+
@@ -265,22 +319,22 @@
Returns:
std.optparse.boolean (opt[, optarg="1"])
- Return a Lua boolean equivalent of various optarg strings.
- Report an option parse error if optarg is not recognised.
+ Return a Lua boolean equivalent of various optarg strings.
+ Report an option parse error if optarg is not recognised.
Pass this as the value function to on when you want various
- truthy or falsey option arguments to be coerced to a Lua true
+ "truthy" or "falsey" option arguments to be coerced to a Lua true
or false respectively in the options table.
iint
- index of last processed element of arglist
+ index of last processed element of arglist
value
either a function to process the option argument,
or a value to store when this flag is encountered
+ (optional)
@@ -414,11 +479,15 @@
Returns:
int
- index of next element of arglist to process
+ index of next element of arglist to process
+
Usage:
+
+
parser:on ({"--long-opt", "-x"}, parser.flag)
+
@@ -436,6 +505,10 @@
Returns:
+
Usage:
+
+
parser:on ("-?", parser.version)
+
@@ -446,13 +519,13 @@
Returns:
Report an option parse error, then exit with status 2.
Use this in your custom option handlers for consistency with the
- error output from built-in optparse error messages.
+ error output from built-in std.optparse error messages.
iint
- index of last processed element of arglist
+ index of last processed element of arglist
value
either a function to process the option argument,
or a forced value to replace the user's option argument.
+ (optional)
@@ -561,11 +639,15 @@
Returns:
int
- index of next element of arglist to process
+ index of next element of arglist to process
+
Usage:
+
+
parser:on ({"-o", "--output"}, parser.required)
+
@@ -583,10 +665,15 @@
Returns:
+
Usage:
+
+
parser:on ("-V", parser.version)
+
Tables
+
@@ -664,7 +751,7 @@
Fields:
If you write your own handlers, or otherwise specify custom
handling of options with on, then whatever value those handlers
- return will be assigned to the respective keys in opts .
+ return will be assigned to the respective keys in opts.
@@ -672,67 +759,17 @@
Fields:
-
-
-
- std.optparse.parser
-
-
- Customized parser for your options.
-
-
This table is returned by OptionParser, and most importantly has
- the parse method you call to fill the opts table according to
- what command-line options were passed to your program.
-
-
-
Fields:
-
-
program
- string
- the first word following Usage: in OptionParser
- spec string
-
-
version
- string
- the last white-space delimited word on the first line
- of text in the spec string
-
-
versiontext
- string
- everything preceding Usage: in the spec string,
- and which will be displayed by the versionon_handler
-
-
helptext
- string
- everything including and following Usage: in the
- spec string and which will be displayed by the help
- on_handler
-
When the automatically assigned option handlers don't do everything
you require, or when you don't want to put an option into the
@@ -741,12 +778,10 @@
Methods
calling this function will replace the automatically assigned handler
with your own.
-
When writing your own handlers for std.optparse:on, you only need
+ to deal with normalised arguments, because combined short arguments
+ (-xyz), equals separators to long options (--long=ARG) are fully
+ expanded before any handler is called.
Parameters:
@@ -757,7 +792,7 @@
Parameters:
handleron_handler
- function to call when any of opts is
+ function to call when any of opts is
encountered
value
@@ -768,6 +803,12 @@
Parameters:
+
Usage:
+
+
+ -- Don't process any arguments after `--`
+ parser:on ('--', parser.finished)
Derived from std.container, and inherits Container's metamethods.
+
Set container prototype.
+
+
Note that Functions listed below are only available from the Set
prototype returned by requiring this module, because Container
objects cannot have object methods.
set2
- table or set
- another set, or table
+ Set
+ another set
Returns:
- true if set1 is a proper subset of set2, false otherwise
+ boolean
+ true if set2 contains all elements in set1
+ but not only those elements, false otherwise
+
Usage:
+
+
+ if set.proper_subset (a, b) then
+ for e in set.elems (set.difference (b, a)) do
+ set.delete (b, e)
+ end
+ end
+ assert (set.equal (a, b))
Derived from std.container, and inherits Container's metamethods.
+
Tree container prototype.
+
+
Note that Functions listed below are only available from the Tree
- prototype return by requiring this module, because Container objects
+ prototype returned by requiring this module, because Container objects
cannot have object methods.
+ --> t = {"one", "three", "five"}
+for leaf in ileaves {"one", {two=2}, {{"three"}, four=4}}, foo="bar", "five"}
+ do
+ t[#t + 1] = leaf
+ end
+
@@ -197,14 +284,14 @@
Returns:
Tree iterator over numbered nodes, in order.
The iterator function behaves like nodes, but only traverses the
- array part of the nodes of tr, ignoring any others.
+ array part of the nodes of tr, ignoring any others.
Parameters:
tr
- tree or table
- tree to iterate over
+ Tree or table
+ tree or tree-like table to iterate over
Note that the tree-path reuses the same table on each iteration, so
you must table.clone a copy if you want to take a snap-shot of the
current state of the tree-path list before the next iteration
@@ -335,7 +419,7 @@
See also:
Parameters:
tr
- tree or table
+ Tree or table
tree or tree-like table to iterate over
The module table returned by std.debug also contains all of the entries
+ from the core debug table. An hygienic way to import this module, then, is
+ simply to override the core debug locally:
-
+
+
+localdebug = require"std.debug"
+
+
+
The behaviour of the functions in this module are controlled by the value
+ of the global _DEBUG. Not setting _DEBUG prior to requiring any of
+ stdlib's modules is equivalent to having _DEBUG = true.
+
+
The first line of Lua code in production quality projects that use stdlib
+ should be either:
+
+
+
+_DEBUG = false
+
+
+
or alternatively, if you need to be careful not to damage the global
+ environment:
+ Provide a deprecated function definition according to _DEBUG.deprecate.
+ You can check whether your covered code uses deprecated functions by
+ setting _DEBUG.deprecate to true before loading any stdlib modules,
+ or silence deprecation warnings by setting _DEBUG.deprecate = false.
+
+
+
Parameters:
+
+
version
+ string
+ first deprecation release version
+
+
name
+ string
+ function name for automatic warning message
+
+
extramsg
+ string
+ additional warning text
+ (optional)
+
+
fn
+ func
+ deprecated function
+
+
+
+
Returns:
+
+
+ a function to show the warning on first call, and hand off to fn
+
+
+
+
+
+
+ argcheck (name, i, expected, actual[, level=2])
+
+
+ Check the type of an argument against expected types.
+ Equivalent to luaL_argcheck in the Lua C API.
+
+
Call argerror if there is a type mismatch.
+
+
Argument actual must match one of the types from in expected, each
+ of which can be the name of a primitive Lua type, a stdlib object type,
+ or one of the special options below:
+
+
#table accept any non-empty table
+any accept any non-nil argument type
+file accept an open file object
+function accept a function, or object with a __call metamethod
+int accept an integer valued number
+list accept a table where all keys are a contiguous 1-based integer range
+#list accept any non-empty list
+object accept any std.Object derived type
+:foo accept only the exact string ":foo", works for any :-prefixed string
+
+
+
The :foo format allows for type-checking of self-documenting
+ boolean-like constant string parameters predicated on nil versus
+ :option instead of false versus true. Or you could support
+ both:
A very common pattern is to have a list of possible types including
+ "nil" when the argument is optional. Rather than writing long-hand
+ as above, append a question mark to at least one of the list types
+ and omit the explicit "nil" entry:
Normally, you should not need to use the level parameter, as the
+ default is to blame the caller of the function using argcheck in
+ error messages; which is almost certainly what you want.
+
+
+
Parameters:
+
+
name
+ string
+ function to blame in error message
+
+
i
+ int
+ argument number to blame in error message
+
+
expected
+ string
+ specification for acceptable argument types
+
+
actual
+ argument passed
+
+
level
+ int
+ call stack level to blame for the error
+ (default 2)
+
+ Raise a bad argument error.
+ Equivalent to luaL_argerror in the Lua C API. This function does not
+ return. The level argument behaves just like the core error
+ function.
+
+
+
Parameters:
+
+
name
+ string
+ function to callout in error message
+
+
i
+ int
+ argument number
+
+
extramsg
+ string
+ additional text to append to message inside parentheses
+ (optional)
+
+
level
+ int
+ call stack level to blame for the error
+ (default 1)
+
+
+
+
+
+
+
Usage:
+
+
+ localfunction slurp (file)
+ local h, err = input_handle (file)
+ if h == nilthen argerror ("std.io.slurp", 1, err, 2) end
+ ...
+
+
+
+
+
+ argscheck (decl, inner)
+
+
+ Wrap a function definition with argument type and arity checking.
+ In addition to checking that each argument type matches the corresponding
+ element in the types table with argcheck, if the final element of
+ types ends with an asterisk, remaining unchecked arguments are checked
+ against that type.
+
+
+
Parameters:
+
+
decl
+ string
+ function type declaration string
+
+
inner
+ func
+ function to wrap with argument checking
+
+
+
+
+
+
+
Usage:
+
+
M.square = argscheck ("util.square (number)", function (n) return n * n end)
+
+
+
debug ()
- The global function debug is an abbreviation for debug.say (1, ...)
+ Equivalent to calling debug.say (1, ...)
@@ -117,20 +422,32 @@
- Print a debugging message.
+ Print a debugging message to io.stderr.
+ Display arguments passed through std.tostring and separated by tab
+ characters when _DEBUG is true and n is 1 or less; or _DEBUG.level
+ is a number greater than or equal to n. If _DEBUG is false or
+ nil, nothing is written.
Parameters:
n
- debugging level, defaults to 1
+ int
+ debugging level, smaller is higher priority
+ (default 1)
...
objects to print (as for print)
@@ -140,6 +457,55 @@
Parameters:
+
Usage:
+
+
+ local _DEBUG = require"std.debug_init"._DEBUG
+ _DEBUG.level = 3
+ say (2, "_DEBUG table contents:", _DEBUG)
+
+
+
+
+
+ toomanyargmsg (name, expect, actual)
+
+
+ Format a standard "too many arguments" error message.
+
+
+
Trace function calls.
Use as debug.sethook (trace, "cr"), which is done automatically
- when _DEBUG.call is set.
+ when _DEBUG.call is set.
Based on test/trace-calls.lua from the Lua distribution.
- To activate debugging set _DEBUG either to any true value
- (equivalent to {level = 1}), or as documented below.
+ Control std.debug function behaviour.
+ To declare debugging state, set _DEBUG either to false to disable all
+ runtime debugging; to any "truthy" value (equivalent to enabling everything
+ except call, or as documented below.
call
+ boolean
do call trace debugging
+ (default false)
-
std
- do standard library debugging (run examples & test code)
+
deprecate
+ if false, deprecated APIs are defined,
+ and do not issue deprecation warnings when used; if nil issue a
+ deprecation warning each time a deprecated api is used; any other
+ value causes deprecated APIs not to be defined at all
+ (default nil)
+
+
level
+ int
+ debugging level
+ (default 1)
+
Usage:
+
+
_DEBUG = { argcheck = false, level = 9 }
+
@@ -201,7 +594,8 @@
Fields:
-generated by LDoc 1.4.2
+generated by LDoc 1.4.3
+Last updated 2015-01-03 20:26:44
- function with pi already bound
+ function with argt arguments already bound
+
Usage:
+
+
cube = bind (std.operator.pow, {[2] = 3})
+
-
- case (with, branches)
+
+ callable (x)
+ Identify callable types.
+
+
+
Parameters:
+
+
x
+ an object or primitive
+
+
+
+
Returns:
+
+
+ true if x can be called, otherwise false
+
-
A rudimentary case statement.
- Match with against keys in branches table, and return the result
- of running the function in the table value for the matching key, or
- the first non-key value function if no key matches.
-
return case (type (object), {
- table = function () return something end,
- string = function () return something else end,
- function (s) error ("unhandled type: "..s) end,
- })
-
+
Usage:
+
+
if callable (functable) then functable (args) end
+
+
+
+
+ case (with, branches)
+
+
+ A rudimentary case statement.
+ Match with against keys in branches table.
Parameters:
@@ -192,7 +247,7 @@
Parameters:
expression to match
branches
- table
+ table
map possible matches to functions
@@ -200,16 +255,34 @@
Parameters:
Returns:
- the return value from function with a matching key, or nil.
+ the value associated with a matching key, or the first non-key
+ value if no key matches. Function or functable valued matches are
+ called using with as the sole argument, and the result of that call
+ returned; otherwise the matching value associated with the matching
+ key is returned directly; or else nil if there is no match and no
+ default.
+
- composition of fn (... (f1) ...): note that this is the reverse
- of what you might expect, but means that code like:
+ function
+ composition of fnN .. fn1: note that this is the
+ reverse of what you might expect, but means that code like:
functional.compose (function (x) return f (x) end,
function (x) return g (x) end))
@@ -256,11 +354,64 @@
Returns:
+
Usage:
+
+
+ vpairs = compose (table.invert, ipairs)
+ for v, i in vpairs {"a", "b", "c"} do process (v, i) end
+
+
+
+
+
+ cond (expr, branch, ...)
+
+
+ A rudimentary condition-case statement.
+ If expr is "truthy" return branch if given, otherwise expr
+ itself. If the return value is a function or functable, then call it
+ with expr as the sole argument and return the result; otherwise
+ return it explicitly. If expr is "falsey", then recurse with the
+ first two arguments stripped.
+
+
+
Parameters:
+
+
expr
+ a Lua expression
+
+
branch
+ a function, functable or value to use if expr is
+ "truthy"
+
+
...
+ additional arguments to retry if expr is "falsey"
+
- Filter an iterator with a predicate.
+ Fold a binary function left associatively.
+ If parameter d is omitted, the first element of t is used,
+ and t treated as if it had been passed without that element.
- Fold a binary function into an iterator.
+ Fold a binary function right associatively.
+ If parameter d is omitted, the last element of t is used,
+ and t treated as if it had been passed without that element.
Parameters:
-
f
- function
+
fn
+ func
+ binary function
d
- initial first argument
+ initial right-most argument
+ (default t[1])
A valid lambda string takes one of the following forms:
+
+
'=expression': equivalent to function (...) return expression end
+
'|args|expression': equivalent to function (args) return expression end
+
+
+
The first form (starting with '=') automatically assigns the first
+ nine arguments to parameters '_1' through '_9' for use within the
+ expression body. The parameter '_1' is aliased to '_', and if the
+ first non-whitespace of the whole expression is '_', then the
+ leading '=' can be omitted.
+
+
The results are memoized, so recompiling a previously compiled
+ lambda string is extremely fast.
+
+
+
Memoize a function, by wrapping it in a functable.
-
To ensure that memoize always returns the same object for the same
- arguments, it passes arguments to normalize (std.string.tostring
- by default). You may need a more sophisticated function if memoize
- should handle complicated argument equivalencies.
+
To ensure that memoize always returns the same results for the same
+ arguments, it passes arguments to fn. You can specify a more
+ sophisticated function if memoize should handle complicated argument
+ equivalencies.
Parameters:
fn
- function that returns a single result
+ func
+ pure function: a function with no side effects
-
normalize
- [opt] function to normalize arguments
+
normfn
+ normalize
+ function to normalize arguments
+ (default std.tostring)
Returns:
+ functable
memoized function
+
Usage:
+
+
local fast = memoize (function (...) --[[ slow code ]]end)
+
-
- memoize_normalize (...)
+
+ nop ()
- Signature of memoize normalize functions.
+ No operation.
+ This function ignores all arguments, and returns no values.
+
+
+
+
+
+
- Functional forms of infix operators.
- Defined here so that other modules can write to it.
+ Zip a table of tables.
+ Make a new table, with lists of elements at the same index in the
+ original table. This function is effectively its own inverse.
-
+
+ table
+ a new table of results from calls to fn with arguments
+ made from all elements the same key in the original tables; effectively
+ the "columns" in a simple list
+ of lists.
+
-
-
After requiring this module, simply referencing symbols in the submodule
- hierarchy will load the necessary modules on demand.
+
Lua Standard Libraries.
+
This module contains a selection of improved Lua core functions, among
+ others.
-
Clients of older releases might be surprised by this new-found hygiene,
- expecting the various changes that used to be automatically installed as
- global symbols, or monkey patched into the core module tables and
- metatables. Sometimes, it's still convenient to do that... when using
- stdlib from the REPL, or in a prototype where you want to throw caution
- to the wind and compatibility with other modules be damned, for example.
- In that case, you can give stdlib permission to scribble all over your
- namespaces with:
+
Also, after requiring this module, simply referencing symbols in the
+ submodule hierarchy will load the necessary modules on demand.
-
local std = require "std".monkey_patch ()
+
By default there are no changes to any global symbols, or monkey
+ patching of core module tables and metatables. However, sometimes it's
+ still convenient to do that: For example, when using stdlib from the
+ REPL, or in a prototype where you want to throw caution to the wind and
+ compatibility with other modules be damned. In that case, you can give
+ stdlib permission to scribble all over your namespaces by using the
+ various monkey_patch calls in the library.
Scribble all over the given namespace, and apply all available
- monkey_patch functions.
+
Apply allmonkey_patch functions. Additionally, for backwards
+ compatibility only, write a selection of sub-module functions into
+ the given namespace.
Parameters:
namespace
- table
+ table
where to install global functions
(default _G)
for v in std.ielems {"a", "b", "c"} do process (v) end
+
+
+
+
+
+ ipairs (t)
+
+
+ An iterator over elements of a sequence, until the first nil value.
+
+
Like Lua 5.1 and 5.3, but unlike Lua 5.2 (which looks for and uses the
+ __ipairs metamethod), this iterator returns successive key-value
+ pairs with integer keys starting at 1, up to the first nil valued
+ pair.
+
+
+
+ -- length of sequence
+ args = {"first", "second", nil, "last"}
+ --> 1=first
+--> 2=second
+for i, v in std.ipairs (args) do
+ print (string.format ("%d=%s", i, v))
+ end
+
+
+
+
+
+ ireverse (t)
+
+
+ Return a new table with element order reversed.
+ Apart from the order of the elments returned, this function follows
+ the same rules as ipairs for determining first and last elements.
+
+
+
+ Enhance core require to assert version number compatibility.
+ By default match against the last substring of (dot-delimited)
+ digits in the module version string.
+
+
+
+ An iterator like ipairs, but in reverse.
+ Apart from the order of the elments returned, this function follows
+ the same rules as ipairs for determining first and last elements.
+
+
+
Lazy load submodules into std on first reference. On initial
- load, std has the usual single version entry, but the __index
- metatable will automatically require submodules on first reference:
-
-
local std = require "std"
- local prototype = std.container.prototype
-
-
+
In addition to the functions documented on this page, and a version
+ field, references to other submodule functions will be loaded on
+ demand.
- the submodule that was loaded to satisfy the missing name
+ table or nil
+ the submodule that was loaded to satisfy the missing
+ name, otherwise nil if nothing was found
+
Usage:
+
+
+ local std = require"std"
+ local prototype = std.object.prototype
+
@@ -247,7 +748,8 @@
Returns:
-generated by LDoc 1.4.2
+generated by LDoc 1.4.3
+Last updated 2015-01-03 20:26:44
The module table returned by std.io also contains all of the entries from
+ the core io module table. An hygienic way to import this module, then,
+ is simply to override core io locally:
namespace
- table
+ table
where to install global functions
(default _G)
@@ -222,61 +306,83 @@
Parameters:
Returns:
- table
- the module table
+ table
+ the std.io module table
+
Usage:
+
+
localio = require"std.io".monkey_patch ()
+
- process_files (f)
+ process_files (fn)
Process files specified on the command-line.
- If no files given, process io.stdin; in list of files,
- - means io.stdin.
+ Each filename is made the default input source with io.input, and
+ then the filename and argument number are passed to the callback
+ function. In list of filenames, - means io.stdin. If no
+ filenames were given, behave as if a single - was passed.
Parameters:
-
f
- function to process files with, which is passed
- (name, arg_no)
+
fn
+ fileprocessor
+ function called for each file argument
Give warning with the name of program and file (if any).
+ Give warning with the name of program and file (if any).
If there is a global prog table, prefix the message with
prog.name or prog.file, and prog.line if any. Otherwise
if there is a global opts table, prefix the message with
opts.program and opts.line if any. std.optparse:parse
returns an opts table that provides the required program
- field, as long as you assign it back to _G.opts:
-
-
local OptionParser = require "std.optparse"
- local parser = OptionParser "eg 0\nUsage: eg\n"
- _G.arg, _G.opts = parser:parse (_G.arg)
- if not _G.opts.keep_going then
- require "std.io".warn "oh noes!"
- end
-
-
-
+ field, as long as you assign it back to _G.opts.
The module table returned by std.math also contains all of the entries from
+ the core math table. An hygienic way to import this module, then, is simply
+ to override the core math locally:
The module table returned by std.package also contains all of the entries
+ from the core package table. An hygienic way to import this module, then, is
+ simply to override core package locally:
- Look for a path segment match of patt in pathstrings.
+ Look for a path segment match of patt in pathstrings.
Parameters:
pathstrings
- string
+ stringpathsep delimited path elements
patt
- string
- a Lua pattern to search for in pathstrings
+ string
+ a Lua pattern to search for in pathstrings
initint
@@ -139,8 +155,8 @@
Parameters:
plainbool
- unless false, treat patt as a plain
- string, not a pattern. Note that if plain is given, then init
+ unless false, treat patt as a plain
+ string, not a pattern. Note that if plain is given, then init
must be given as well.
(default false)
@@ -155,6 +171,10 @@
Returns:
+
Usage:
+
+
i, s = find (package.path, "^[^" .. package.dirsep .. "/]")
+
@@ -168,17 +188,17 @@
Returns:
Parameters:
pathstrings
- string
+ string
a package.path like string
posint
- element index at which to insert value, where n is
+ element index at which to insert value, where n is
the number of elements prior to insertion
(default n+1)
value
- string
+ string
new path element to insert
@@ -186,12 +206,16 @@
Parameters:
Returns:
- string
+ string
a new string with the new element inserted
+
All global variables must be 'declared' through a regular
assignment (even assigning nil will do) in a top-level
- chunk before being used anywhere or assigned to inside a function.
- From Lua distribution (etc/strict.lua).
+ chunk before being used anywhere or assigned to inside a function.
+
+
To use this module, just require it near the start of your program.
If you require "std", the contents of this module are all available
- in the std.string table.
+
The module table returned by std.string also contains all of the entries
+ from the core string table. An hygienic way to import this module, then, is
+ simply to override the core string locally:
-
However, this module also contains references to the Lua core string
- table entries, so it's safe to load it like this:
-
local string = require "std.string"
-
-
-
Of course, if you do that you'll lose references to any core string
- functions overwritten by std.string , so you might want to save any
- that you want access to before you overwrite them.
-
-
If your code does not require "std" anywhere, then you'll also need
- to manually overwrite string functions in the global namespace if you
- want to use them from there:
-
-
local assert, tostring = string.assert, string.tostring
-
-
-
And finally, to use the string metatable improvements with all core
- strings, you'll need to merge this module's metatable into the core
- string metatable (again, require "std" does this automatically):
-
+ Split a string at a given separator.
+ Separator is a Lua pattern, so you have to escape active characters,
+ ^$()%.[]*+-? with a % prefix to match a literal character in s.
function slow_identity (x) return functional.eval (pickle (x)) end
+
+
+
Types
+
+
+
-
- split (s[, sep="%s*"])
+
+ closetablecb (t)
- Split a string at a given separator.
- Separator is a Lua pattern, so you have to escape active characters,
- ^$()%.[]*+-? with a % prefix to match a literal character in s.
+ Signature of render close table callback.
- Remove leading and trailing matter from a string.
+ Signature of render pair callback.
+ Trying to re-render key or value here will break recursion
+ detection, use strkey and strvalue pre-rendered values instead.
The module table returned by std.table also contains all of the entries from
+ the core table module. An hygienic way to import this module, then, is simply
+ to override the core table locally:
+ Enhance core table.insert to return its result.
+ If pos is not given, respect __len metamethod when calculating
+ default append. Also, diagnose out of bounds pos arguments
+ consistently on any supported version of Lua.
+
+
+
- An iterator like ipairs, but in reverse.
+ Enhance core table.remove to respect __len when pos is omitted.
+ Also, diagnose out of bounds pos arguments consistently on any supported
+ version of Lua.
pos
+ int
+ index from which to remove an element
+ (default len (t))
+
+
+
+
Returns:
+
+
+ removed value, or else nil
+
+
+
+
+
Usage:
+
+
+ --> {1, 2, 5}
+ t = {1, 2, "x", 5}
+ remove (t, 3) == "x"and t
+
+
+
+
+
+ shape (dims, t)
+
+
+ Shape a table according to a list of dimensions.
+
+
Dimensions are given outermost first and items from the original
+ list are distributed breadth first; there may be one 0 indicating
+ an indefinite number. Hence, {0} is a flat list,
+ {1} is a singleton, {2, 0} is a list of
+ two lists, and {0, 2} is a list of pairs.
+
+
Algorithm: turn shape into all positive numbers, calculating
+ the zero if necessary and making sure there is at most one;
+ recursively walk the shape, adding empty tables until the bottom
+ level is reached at which point add table items instead, using a
+ counter to walk the flattened original list.
+
+
+
- table
+ tableobj with non-private fields from src merged,
and a metatable with private fields (if any) merged, both sets
of keys renamed according to map
@@ -348,7 +348,7 @@
Usage:
function.
Additionally, this function returns the results of ??? for
- file objects, or type otherwise.
+ file objects, or type otherwise.
program
- string
+ string
the first word following "Usage:" from spec
version
- string
+ string
the last white-space delimited word on the first line
of text from spec
versiontext
- string
+ string
everything preceding "Usage:" from spec, and
which will be displayed by the versionon_handler
helptext
- string
+ string
everything including and following "Usage:" from
spec string and which will be displayed by the helpon_handler
@@ -294,7 +294,7 @@
Buffers are mutable by default, but being based on objects, they can
+ also be used in a functional style:
+
+
+
+local StrBuf = require"std.strbuf" {}
+local a = StrBuf {"a"}
+local b = a:concat "b"-- mutate *a*
+print (a, b) --> ab ab
+local c = a {} .. "c"-- copy and append
+print (a, c) --> ab abc
+
+
_type
- string
+ string
object name
(default "StrBuf")
@@ -152,9 +162,11 @@
Usage:
local std = require"std"local StrBuf = std.strbuf {}
- local buf = StrBuf {"initial buffer contents"}
- buf = buf .. "append to buffer"
- print (buf) -- implicit `tostring` concatenates everything
+ local a = {1, 2, 3}
+ local b = {a, "five", "six"}
+ a = a .. 4
+ b = b:concat "seven"
+ print (a, b) --> 1234 1234fivesixseven
os.exit (0)
@@ -165,17 +177,18 @@
Functions
- std.strbuf.concat (s)
+ std.strbuf.concat (x)
- Add a string to a buffer.
+ Add a object to a buffer.
+ Elements are stringified lazily, so if add a table and then change
+ its contents, the contents of the buffer will be affected too.
A very common pattern is to have a list of possible types including
"nil" when the argument is optional. Rather than writing long-hand
- as above, append a question mark to at least one of the list types
- and omit the explicit "nil" entry:
+ as above, prepend a question mark to the list of types and omit the
+ explicit "nil" entry:
-
Normally, you should not need to use the level parameter, as the
@@ -294,7 +294,7 @@
Usage:
Parameters:
name
- string
+ string
function to blame in error message
i
@@ -302,7 +302,7 @@
Parameters:
argument number to blame in error message
expected
- string
+ string
specification for acceptable argument types
actual
@@ -341,7 +341,7 @@
Usage:
Parameters:
name
- string
+ string
function to callout in error message
i
@@ -349,7 +349,7 @@
Parameters:
argument number
extramsg
- string
+ string
additional text to append to message inside parentheses
(optional)
@@ -378,17 +378,41 @@
Usage:
argscheck (decl, inner)
- Wrap a function definition with argument type and arity checking.
+
+
Wrap a function definition with argument type and arity checking.
In addition to checking that each argument type matches the corresponding
element in the types table with argcheck, if the final element of
- types ends with an asterisk, remaining unchecked arguments are checked
- against that type.
+ types ends with an ellipsis, remaining unchecked arguments are checked
+ against that type:
+
+
format = argscheck ("string.format (string, ?any...)", string.format)
+
+
+
If an argument can be omitted entirely, then put its type specification
+ in square brackets:
- table
+ table
a new table of results from calls to fn with arguments
made from all elements the same key in the original tables; effectively
the "columns" in a simple list
@@ -969,7 +969,7 @@
file
- file or string
+ file or string
file handle or name;
if file is a file handle, that file is closed after reading
(default io.input())
@@ -396,7 +396,7 @@
file
- file or string
+ file or string
file handle or name;
if file is a file handle, that file is closed after reading
(default io.input())
@@ -507,7 +507,7 @@
- table
+ tableobj with non-private fields from src merged,
and a metatable with private fields (if any) merged, both sets
of keys renamed according to map
@@ -348,7 +348,7 @@
Usage:
function.
Additionally, this function returns the results of ??? for
- file objects, or type otherwise.
+ file objects, or type otherwise.
program
- string
+ string
the first word following "Usage:" from spec
version
- string
+ string
the last white-space delimited word on the first line
of text from spec
versiontext
- string
+ string
everything preceding "Usage:" from spec, and
which will be displayed by the versionon_handler
helptext
- string
+ string
everything including and following "Usage:" from
spec string and which will be displayed by the helpon_handler
@@ -294,7 +294,7 @@
- table
+ table
a new table of results from calls to fn with arguments
made from all elements the same key in the original tables; effectively
the "columns" in a simple list
@@ -969,7 +969,7 @@
file
- file or string
+ file or string
file handle or name;
if file is a file handle, that file is closed after reading
(default io.input())
@@ -396,7 +396,7 @@
file
- file or string
+ file or string
file handle or name;
if file is a file handle, that file is closed after reading
(default io.input())
@@ -507,7 +507,7 @@
- Print a debugging message to io.stderr.
- Display arguments passed through std.tostring and separated by tab
- characters when _DEBUG is true and n is 1 or less; or _DEBUG.level
- is a number greater than or equal to n. If _DEBUG is false or
- nil, nothing is written.
+ Format a type mismatch error.
Parameters:
-
n
- int
- debugging level, smaller is higher priority
- (default 1)
+
expected
+ string
+ a pipe delimited list of matchable types
-
...
- objects to print (as for print)
+
actual
+ the actual argument to match with
+
+
index
+ number
+ erroring container element index
+ (optional)
+
Returns:
+
+ string
+ formatted extramsg for this mismatch for argerror
+
+
- Format a standard "too many arguments" error message.
+ Compact permutation list into a list of valid types at each argument.
+ Eliminate bracketed types by combining all valid types at each position
+ for all permutations of typelist.
- string
- standard "too many arguments" error message
+ list
+ valid types for each positional parameter
+
+
+
+
+ say ([n=1], ...)
+
+
+ Print a debugging message to io.stderr.
+ Display arguments passed through std.tostring and separated by tab
+ characters when _DEBUG is true and n is 1 or less; or _DEBUG.level
+ is a number greater than or equal to n. If _DEBUG is false or
+ nil, nothing is written.
+
+
+
Parameters:
+
+
n
+ int
+ debugging level, smaller is higher priority
+ (default 1)
+
+ if maxn (argt) > 7then
+ argerror ("sevenses", 8, extramsg_toomany ("argument", 7, maxn (argt)))
+ end
+
+
+
+
+
+ getfenv
+
+
+ Extend debug.getfenv to unwrap functables correctly.
+
+
+
+
fn
+ int, function or functable
+ target function, or stack level
+
+
+
+
+
+
+
+
+
+
+ resulterror
+
+
+ Raise a bad result error.
+ Like argerror for bad results. This function does not
+ return. The level argument behaves just like the core error
+ function.
+
+
+
+
name
+ string
+ function to callout in error message
+
+
i
+ int
+ argument number
+
+
extramsg
+ string
+ additional text to append to message inside parentheses
+ (optional)
+
+
level
+ int
+ call stack level to blame for the error
+ (default 1)
+
+
+
+
+
+
+
Usage:
+
+
+ localfunction slurp (file)
+ local h, err = input_handle (file)
+ if h == nilthen argerror ("std.io.slurp", 1, err, 2) end
+ ...
+
+
+
+
+
+ setfenv
+
+
+ Extend debug.setfenv to unwrap functables correctly.
+
+
+
+ An iterator like npairs, but in reverse.
+ Apart from the order of the elments returned, this function follows
+ the same rules as npairs for determining first and last elements.
+
+
+