Module ml
Microlight - a very compact Lua utilities module
Steve Donovan, 2012; License MIT
String utilties
| split (s, re, n) | split a delimited string into an array of strings. |
| escape (s) | escape any 'magic' pattern characters in a string. |
| expand (s, subst) | expand a string containing any ${var} or $var. |
| readfile (filename, is_bin) | return the contents of a file as a string |
| writefile (filename, str, is_bin) | write a string to a file, |
File and Path functions
| exists (filename) | Does a file exist? |
| splitpath (P) | split a path into directory and file part. |
| splitext (P) | split a path into root and extension part. |
Extended table functions
| tstring (t, how) | return a string representation of a Lua value. |
| collect (...) | collect a series of values from an interator. |
| collectuntil (f, ...) | collect from an interator up to a condition. |
| collectn (n, ...) | collect n values from an interator. |
| collect2nd (...) | collect the second value from a iterator. |
| mapextend (dest, j, nilv, f, t, ...) | extend a table by mapping a function over another table. |
| imap (f, t, ...) | map a function over an array. |
| transform (f, t, ...) | apply a function to each element of an array. |
| imap2 (f, t1, t2, ...) | map a function over values from two arrays. |
| imapfilter (f, t, ...) | map a function over an array only keeping non-nil values. |
| ifilter (t, pred, ...) | filter an array using a predicate. |
| ifind (t, pred, ...) | find an item in an array using a predicate. |
| indexof (t, value, cmp) | return the index of an item in an array. |
| sub (t, i1, i2) | return a slice of an array. |
| removerange (tbl, start, finish) | delete a range of values from an array. |
| insertvalues (dest, index, src, overwrite) | copy values from src into dest starting at index. |
| extend (t, ...) | extend an array using values from other tables. |
| indexby (t, keys) | make an array of indexed values. |
| range (x1, x2, d) | create an array of numbers from start to end. |
| update (t, ...) | add the key/value pairs of arrays to the first array. |
| makemap (t, tv) | make a table from an array of keys and an array of values. |
| invert (t) | make a set from an array. |
| keys (t) | extract the keys of a table as an array. |
| issubset (t, other) | are all the values of other in t? |
| containskeys | are all the keys of other in t? |
| count (t) | return the number of keys in this table, or members in this set. |
| equalkeys (t, other) | do these tables have the same keys? |
Functional helpers
| throw (f) | create a function which will throw an error on failure. |
| bind1 (f, v) | bind the value v to the first argument of function f. |
| bind2 (f, v) | bind the value v to the second argument of function f. |
| compose (f1, f2) | compose two functions. |
| take2 (f) | a function returning the second value of f |
| callable (obj) | is the object either a function or a callable object?. |
| map2fun (t) | create a callable from an indexable object. |
| fun2map (f) | create an indexable object from a callable. |
| function_arg (f) | defines how we convert something to a callable. |
| memoize (func) | 'memoize' a function (cache returned value for next call). |
Classes
| class (base) | create a class with an optional base class. |
| Array | a simple Array class. |
String utilties
- split (s, re, n)
-
split a delimited string into an array of strings.
Parameters:
- s The input string
- re A Lua string pattern; defaults to '%s+'
- n optional maximum number of splits
Returns:
-
an array of strings
- escape (s)
-
escape any 'magic' pattern characters in a string.
Useful for functions like string.gsub and string.match which
always work with Lua string patterns.
For any s,
s:match('^'..escape(s)..'$') == sistrue.Parameters:
- s The input string
Returns:
-
an escaped string
- expand (s, subst)
-
expand a string containing any
${var}or$var. Substitution values should be only numbers or strings. However, you should pick either one consistently!Parameters:
- s the string
- subst either a table or a function (as in string.gsub )
Returns:
-
expanded string
- readfile (filename, is_bin)
-
return the contents of a file as a string
Parameters:
- filename The file path
- is_bin open in binary mode, default false
Returns:
-
file contents, or nil,error
- writefile (filename, str, is_bin)
-
write a string to a file,
Parameters:
- filename The file path
- str The string
- is_bin open in binary mode, default false
Returns:
-
true or nil,error
File and Path functions
- exists (filename)
-
Does a file exist?
Parameters:
- filename a file path
Returns:
-
the file path, otherwise nil
Usage:
file = exists 'readme' or exists 'readme.txt' or exists 'readme.md'
- splitpath (P)
-
split a path into directory and file part.
if there's no directory part, the first value will be the empty string.
Handles both forward and back-slashes on Windows.
Parameters:
- P A file path
Returns:
- the directory part
- the file part
- splitext (P)
-
split a path into root and extension part.
if there's no extension part, the second value will be empty
Parameters:
- P A file path
Returns:
- the name part
- the extension
Extended table functions
'array' here is shorthand for 'array-like table'; these functions only operate over the numeric1..#t range of a table and are
particularly efficient for this purpose.
- tstring (t, how)
-
return a string representation of a Lua value.
Cycles are detected, and the result can be optionally indented nicely.
to
indent.Parameters:
- t the table
- how (optional) a table with fields `spacing' and 'indent', or a string corresponding
Returns:
-
a string
- collect (...)
-
collect a series of values from an interator.
Parameters:
- ... iterator
Returns:
-
array-like table
Usage:
collect(pairs(t)) is the same as keys(t)
- collectuntil (f, ...)
-
collect from an interator up to a condition.
If the function returns true, then collection stops.
Parameters:
- f predicate receiving (value,count)
- ... iterator
Returns:
-
array-like table
- collectn (n, ...)
-
collect
nvalues from an interator.Parameters:
- n number of values to collect
- ... iterator
Returns:
-
array-like table
- collect2nd (...)
-
collect the second value from a iterator.
If the second value is
nil, it won't be collected!Parameters:
- ... iterator
Returns:
-
array-like table
Usage:
collect2nd(pairs{one=1,two=2}) is {1,2} or {2,1} - mapextend (dest, j, nilv, f, t, ...)
-
extend a table by mapping a function over another table.
Parameters:
- dest destination table
- j start index in destination
- nilv
default value to use if function returns
nil - f the function
- t source table
- ... extra arguments to function
- imap (f, t, ...)
-
map a function over an array.
The output must always be the same length as the input, so
any
nilvalues are mapped tofalse.Parameters:
- f a function of one or more arguments
- t the array
- ... any extra arguments to the function
Returns:
-
a new array with elements
f(t[i],...) - transform (f, t, ...)
-
apply a function to each element of an array.
Parameters:
- f a function of one or more arguments
- t the array
- ... any extra arguments to the function
Returns:
-
the transformed array
- imap2 (f, t1, t2, ...)
-
map a function over values from two arrays.
Length of output is the size of the smallest array.
Parameters:
- f a function of two or more arguments
- t1 first array
- t2 second array
- ... any extra arguments to the function
Returns:
-
a new array with elements
f(t1[i],t2[i],...) - imapfilter (f, t, ...)
-
map a function over an array only keeping non-
nilvalues.Parameters:
- f a function of one or more arguments
- t the array
- ... any extra arguments to the function
Returns:
-
a new array with elements
v = f(t[i],...) such that v ~= nil - ifilter (t, pred, ...)
-
filter an array using a predicate.
Parameters:
- t a table
- pred
a function that must return
nilorfalseto exclude a value - ... any extra arguments to the predicate
Returns:
-
a new array such that
pred(t[i])evaluates as true - ifind (t, pred, ...)
-
find an item in an array using a predicate.
Parameters:
- t the array
- pred a function of at least one argument
- ... any extra arguments
Returns:
-
the item value, or
nilUsage:
ifind({{1,2},{4,5}},'X[1]==Y',4) is {4,5} - indexof (t, value, cmp)
-
return the index of an item in an array.
Parameters:
- t the array
- value item value
- cmp
optional comparison function (default is
X==Y)
Returns:
-
index, otherwise
nil - sub (t, i1, i2)
-
return a slice of an array.
Like string.sub , the end index may be negative.
Parameters:
- t the array
- i1 the start index, default 1
- i2 the end index, default #t
Returns:
-
an array of
t[i]forifromi1toi2inclusive - removerange (tbl, start, finish)
-
delete a range of values from an array.
Parameters:
- tbl the array
- start start index
- finish end index (like ml.sub )
- insertvalues (dest, index, src, overwrite)
-
copy values from
srcintodeststarting atindex. By default, it moves up elements ofdestto make room.Parameters:
- dest destination array
- index start index in destination
- src source array
- overwrite write over values
- extend (t, ...)
-
extend an array using values from other tables.
Extracting and Mapping
Parameters:
- t the array to be extended
- ... the other arrays
Returns:
-
the extended array
- indexby (t, keys)
-
make an array of indexed values.
Generalized table indexing. Result will only contain
values for keys that exist.
Parameters:
- t a table
- keys an array of keys or indices
Returns:
-
an array
Lsuch thatL[keys[i]]Usage:
indexby({one=1,two=2},{'one','three'}) is {1}indexby({10,20,30,40},{2,4}) is {20,40}
- range (x1, x2, d)
-
create an array of numbers from start to end.
With one argument it goes
1..x1.dmay be a floating-point fractionParameters:
- x1 start value
- x2 end value
- d increment (default 1)
Returns:
-
array of numbers
Usage:
range(2,10) is {2,3,4,5,6,7,8,9,10}range(5) is {1,2,3,4,5}
- update (t, ...)
-
add the key/value pairs of arrays to the first array.
For sets, this is their union. For the same keys,
the values from the first table will be overwritten.
Parameters:
- t table to be updated
- ... tables containg more pairs to be added
Returns:
-
the updated table
- makemap (t, tv)
-
make a table from an array of keys and an array of values.
Parameters:
- t an array of keys
- tv an array of values
Returns:
-
a table where
{[t[i]]=tv[i]}Usage:
makemap({'power','glory'},{20,30}) is {power=20,glory=30} - invert (t)
-
make a set from an array.
The values are the original array indices.
Parameters:
- t an array of values
Returns:
-
a table where the keys are the indices in the array.
Usage:
invert{'one','two'} is {one=1,two=2} - keys (t)
-
extract the keys of a table as an array.
Parameters:
- t a table
Returns:
-
an array of keys
- issubset (t, other)
-
are all the values of
otherint?Parameters:
- t a set
- other a possible subset
Returns:
-
bool
- containskeys
-
are all the keys of
otherint?:
- t a table
- other another table
- count (t)
-
return the number of keys in this table, or members in this set.
Parameters:
- t a table
Returns:
-
int
key count
- equalkeys (t, other)
-
do these tables have the same keys?
THis is set equality.
Parameters:
- t a table
- other a table
Returns:
-
true or false
Functional helpers
- throw (f)
-
create a function which will throw an error on failure.
Parameters:
- f a function that returns nil,err if it fails
Returns:
-
an equivalent function that raises an error
- bind1 (f, v)
-
bind the value
vto the first argument of functionf.Parameters:
- f a function of at least one argument
- v a value
Returns:
-
a function of one less argument
Usage:
(bind1(string.match,'hello')('^hell') == 'hell' - bind2 (f, v)
-
bind the value
vto the second argument of functionf.Parameters:
- f a function of at least one argument
- v a value
Returns:
-
a function of one less argument
Usage:
(bind2(string.match,'^hell')('hello') == 'hell' - compose (f1, f2)
-
compose two functions.
For instance,
printfcan be defined ascompose(io.write,string.format)Parameters:
- f1 a function
- f2 a function
Returns:
f1(f2(...)) - take2 (f)
-
a function returning the second value of
fParameters:
- f a function returning at least two values
Returns:
-
a function returning second of those values
Usage:
take2(splitpath) is basename
- callable (obj)
-
is the object either a function or a callable object?.
Parameters:
- obj Object to check.
Returns:
-
true if callable
- map2fun (t)
-
create a callable from an indexable object.
Parameters:
- t a table or other indexable object.
- fun2map (f)
-
create an indexable object from a callable.
Parameters:
- f a callable of one argument.
- function_arg (f)
-
defines how we convert something to a callable.
Currently, anything that matches callable or is a string lambda. These are expressions with any of the placeholders,
X,YorZcorresponding to the first, second or third argument to the function.This can be overriden by people wishing to extend the idea of 'callable' in this library.
Parameters:
- f a callable or a string lambda.
Returns:
-
a function
Raises:
error iffis not callable in any way, or errors in string lambda.Usage:
function_arg('X+Y')(1,2) == 3 - memoize (func)
-
'memoize' a function (cache returned value for next call).
This is useful if you have a function which is relatively expensive,
but you don't know in advance what values will be required, so
building a table upfront is wasteful/impossible.
Parameters:
- func a function of at least one argument
Returns:
-
a function with at least one argument, which is used as the key.
Classes
- class (base)
-
create a class with an optional base class.
See Classes The resulting table can be called to make a new object, which invokes an optional constructor named
_init. If the base class has a constructor, you can call it as thesuper()method. Every class has a_classand a maybe-nil_basefield, which can be accessed through the object.All metamethods are inherited. The class is given a function
Klass.classof(obj).Parameters:
- base optional base class
Returns:
-
the callable metatable representing the class
- Array
-
a simple Array class.
Array Class
table functions:
sort,concat,insert,remove,insertasappend.ml functions: ifilter as
filter,imap asmap,sub ,indexby ,range , indexof ,ifind asfind,extend ,split and collect .The
sortedmethod returns a sorted copy.Concatenation, equality and custom tostring is defined.
This implementation has covariant methods; so that methods like
mapand sub will return an object of the derived type, not Array