[
  {
    "path": "compress.lua",
    "content": "io.output 'compressed/ml.lua'\r\nfor line in io.lines 'ml.lua' do\r\n   if not (line:match '^%s*$' or line:match '^%-%-') then\r\n\tline = line:gsub('^%s*','')\r\n\tio.write(line,'\\n')\r\n   end\r\nend\r\nio.close()\r\n\r\n"
  },
  {
    "path": "config.ld",
    "content": "project='Microlight'\nfile='ml.lua'\ndescription='Compact Lua Utility Library'\nformat='markdown'\ntitle='Microlight'\nreadme='readme.md'\n\n"
  },
  {
    "path": "examples/test.lua",
    "content": "local ml = require 'ml'\nlocal A = ml.Array\nunpack = unpack or table.unpack\n\nml.import(_G,ml)\n\nlocal teq = Array.__eq\n\nfunction asserteq (v1,v2)\n    local t1,t2 = type(v1),type(v2)\n    local check = false\n    if t1 == t2 then\n        if t1 ~= 'table' then check = v1 == v2\n        else check = teq(t1,t2)\n        end\n    end\n    if not check then\n        error(\"assertion failed\\nA \"..tstring(v1)..\"\\nB \"..tstring(v2),2)\n    end\nend\n\nt = {one={two=2},10,20,{1,2}}\n\nassert(tstring(t) == \"{10,20,{1,2},one={two=2}}\")\n\nlocal charmap = string.char(unpack(range(0,255)))\nassert((\"aa\"..charmap..\"bb\"):match(escape(charmap)) == charmap)\n\n\nassert(split('hello','')[1] == 'hello')\n\nlocal a123 = {'one','two','three'}\n\nasserteq(split('one,two,three',','),a123)\n\nasserteq(split('one,,two',','),{'one','','two'})\n\n-- trailing delimiter ignored!\nasserteq(split('one,two,three,',','),a123)\n\n-- delimiter is a Lua pattern (use escape if necessary!)\n-- splitting tokens separated by commas and/or spaces\nasserteq(split('one, two,three  ','[,%s]+'),a123)\nasserteq(split('one two  three  ','[,%s]+'),a123)\n\n--- paths\n-- note that forward slashes also work on Windows\nlocal P = '/users/steve/bonzo.dog'\n\nlocal path,name = ml.splitpath(P)\n\nasserteq(path,'/users/steve')\nasserteq(name,'bonzo.dog')\n\nlocal basename,ext = ml.splitext(P)\n\nasserteq(basename,'/users/steve/bonzo')\nasserteq(ext,'.dog')\n\n\nt = {10,20,30,40}\n\nasserteq(sub(t,1,2),{10,20})\n\nasserteq(indexof(t,20),2)\n\n-- indexof may have an optional specialized equality function\nidx = indexof({'one','two','three'},'TWO',function(s1,s2)\n    return s1:upper()==s2:upper()\n  end\n)\nasserteq (idx,2)\n\n-- generalization of table indexing\nasserteq(indexby(t,{1,4}),{10,40})\n\n-- generating a range of numbers (Array.range does this but returns an Array)\nasserteq(range(1,4),{1,2,3,4})\n\n-- append extra elements to t\nextend(t,{50,60},{70,80})\n\nasserteq(sub(t,4),{40,50,60,70,80})\n\nm = makemap(t)\n\nassert(m[50]==5 and m[20]==2)\n\nassert(count(m) == #t)\n\ntt = keys(m)\n\n-- this isn't necessarily true because there is no guaranteed key order\n--assert(tt==A(t))\n\n-- this only compares keys, so the actual values don't matter\nassert(issubset({a=1,b=2,c=3},{a='hello'}))\n\n\nremoverange(t,2,3)\nasserteq(t,{10,40,50,60})\n\n-- insert some values at the start\n-- (insertvalues in general can be expensive when actually inserting)\ninsertvalues(t,1,{2,5})\nasserteq(t,{2,5,10,40,50,60})\n\n-- copy some values without inserting (overwrite)\ninsertvalues(t,2,{11,12,13},true)\nasserteq(t,{2,11,12,13,50,60})\n\n-- make a new array containing all the even numbers\n-- the filter method is equivalent to ml.ifilter\nta = A(t)\na2 = ta:filter(function(x) return x % 2 == 0 end)\n\nasserteq(a2,A{2,12,50,60})\n\nta = A{10,2,5,4,9}\nta:sort()\nasserteq(ta,A{2,4,5,9,10})\n\n-- make a new array by mapping the square function over its elements\n-- the map method is equivalent to ml.imap\na3 = Array.range(1,4):map(function(x) return x*x end)\n\nasserteq(a3,A{1,4,9,16})\n\n-- the result of a map must have the same size as the input,\n-- and must be a valid sequence, so `nil` becomes `false`\nt = {'1','foo','10'}\nres = imap(tonumber,t)\nasserteq(res,{1,false,10})\n\n-- Array objects understand concatenation!\nasserteq(A{1,2}..A{3,4},Array.range(1,4))\n\na = Array.range(1,10)\n\nassert(a:sub(2,4) == A{2,3,4})\n\nt = {one=1,two=2}\nk = keys(t)\n-- no guarantee of order!\nassert(teq(k,{'one','two'}) or teq(k,{'two','one'}))\n\n-- ml does not give us a corresponding values() function, but\n-- collect2nd does the job\nv = collect2nd(pairs(t))\nassert(teq(v,{1,2}) or teq(v,{2,1}))\n\n----- functional helpers\n\nassert( bind1(string.match,'hello')('^hell') == 'hell')\n\nisdigits = bind2(string.match,'^%d+$')\nassert( isdigits '23105')\nassert( not isdigits '23x5' )\n\nlocal k = 0\n\nf = memoize(function(s)\n    k = k + 1\n    return s:upper()\nend)\n\nassert(f'one' == 'ONE')\nassert(f'one' == 'ONE')\nassert(k == 1)\n\n-- string lambdas ---\n-- Contain up to three placeholders: X,Y and Z\n\nlocal a = A{1,2,3,4}\n\nlocal plus1 = a:map 'X+1'\n\nassert (plus1 == A{2,3,4,5})\n\n-- can use extra placeholder to match extra arg...\nassert(a:map('X+Y',1), plus1)\n\nval = A{'ml','test','util'}:map('X..Y','.lua'):filter(exists)\nassert(val == A{'ml.lua'})\n\n--- classes ------\n\nC = class()\n\n--- conventional name for constructor --\nfunction C:_init (name)\n    self.name = name\nend\n\n-- can define metamethods as well as plain methods\nfunction C:__tostring ()\n    return 'name '..self.name\nend\n\nfunction C:__eq (other)\n    return self.name == other.name\nend\n\nc = C('Jones')\nassert(tostring(c) == 'name Jones')\n\n-- inherited classes inherit constructors and metamethods\nD = class(C)\n\nd = C('Jane')\nassert(tostring(d) == 'name Jane')\nassert(d == C 'Jane')\n\n-- if you do have a constructor, call the base constructor explicitly\nE = class(D)\n\nfunction E:_init (name,nick)\n    self:super(name)\n    self.nick = nick\nend\n\n-- call methods of base class explicitly\n-- (you can also use `self._class`)\n\nfunction E:__tostring ()\n    return D.__tostring(self)..' nick '..self.nick\nend\n\nasserteq(tostring(E('Jones','jj')),'name Jones nick jj')\n\n--- Subclassing Array\n\nStrings = class(Array)\n\n-- can always use the functional helpers to make new methods\n-- bind2 is useful with methods\n\nStrings.match = bind2(Strings.filter,string.match)\n\na = Strings{'one','two','three'}\nasserteq(a:match 'e$',{'one','three'})\n\n---  for numerical operations\n\nNA = class(Array)\n\nlocal function mapm(a1,op,a2)\n  local M = type(a2)=='table' and Array.map2 or Array.map\n  return M(a1,op,a2)\nend\n\n--- elementwise arithmetric operations\nfunction NA.__unm(a) return a:map '-X' end\nfunction NA.__pow(a,s) return a:map 'X^Y' end\nfunction NA.__add(a1,a2) return mapm(a1,'X+Y',a2) end\nfunction NA.__sub(a1,a2) return mapm(a1,'X-Y',a2) end\nfunction NA.__div(a1,a2) return mapm(a1,'X/Y',a2) end\nfunction NA.__mul(a1,a2) return mapm(a2,'X*Y',a1) end\n\nfunction NA:minmax ()\n    local min,max = math.huge,-math.huge\n    for i = 1,#self do\n        local val = self[i]\n        if val > max then max = val end\n        if val < min then min = val end\n    end\n    return min,max\nend\n\nfunction NA:sum ()\n    local res = 0\n    for i = 1,#self do\n        res = res + self[i]\n    end\n    return res\nend\n\nfunction NA:normalize ()\n    return self:transform('X/Y',self:sum())\nend\n\nNA:mappers {\n    tostring = tostring,\n    format = string.format\n}\n\nasserteq(NA{10,20}:tostring(),{'10','20'})\n\nasserteq(NA{1,2.2,10}:format '%5.1f',{\"  1.0\",\"  2.2\",\" 10.0\"})\n\n--- arithmetric --\n\nasserteq(NA{1,2,3} + NA{10,20,30}, NA{11,21,31})\n\n-- note 2nd arg may be a scalar\nasserteq(NA{1,2,3}+1, NA{2,3,4})\n\nasserteq(NA{10,20}/2, NA{5,10})\n\n-- except for * where the 1st arg can be a scalar...\nasserteq(2*NA{1,2,3},NA{2,4,6})\n\nasserteq(-NA{1,2},NA{-1,-2})\n\n-- subclasses of Array have covariant methods, so that e.g. sub\n-- is returning an actual NA object.\nlocal mi,ma = NA{1,6,11,2,20}:sub(1,3):minmax()\nassert(mi == 1 and ma == 11)\n\n\n-- properties\n\nlocal props = require 'ml_properties'\n\nP = class()\n\nfunction P:update (k,v)\n    last_set = k\nend\n\n-- any explicit setters will be called on construction\nfunction P:set_name (name)\n\n    self.myname = name\nend\n\nfunction P:get_name ()\n    last_get = 'name'\n    return self.myname\nend\n\n-- have to call this after any setters or getters are defined...\nprops(P,{\n    __update = P.update; -- will be called after setting _props\n    enabled = true,\n    visible = false,\n    name = 'foo',\n})\n\np = P()\n\nasserteq (p,{myname=\"foo\",_enabled=true,_visible=false})\n\nassert(p.enabled==true and p.visible==false)\n\np.visible = true\nasserteq(last_set,'visible')\n\np.name = 'boo'\n\nassert (p.name == 'boo' and last_get == 'name')\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "microlight-1.1-1.rockspec",
    "content": "package = \"microlight\"\nversion = \"1.1-1\"\nsource = {\n   url = \"git://github.com/stevedonovan/Microlight.git\",\n   tag = \"1.1\",\n   dir = \".\"\n}\ndescription = {\n   summary = \"A compact set of Lua utility functions.\",\n   detailed = [[\n      Microlight provides a table stringifier, string spit and substitution,\n      useful table operations, basic class support and some functional helpers.\n   ]],\n   homepage = \"http://stevedonovan.github.com/microlight/\",\n   license = \"MIT/X11\",\n   maintainer = \"steve.j.donovan@gmail.com\",   \n}\ndependencies = {\n   \"lua >= 5.1\",\n}\nbuild = {\n   type = \"builtin\",\n   modules = {\n      ml = \"ml.lua\" ,\n   }\n}\n"
  },
  {
    "path": "ml.lua",
    "content": "-----------------\n-- Microlight - a very compact Lua utilities module\n--\n-- Steve Donovan, 2012; License MIT\n-- @module ml\n\nlocal ml = {}\nlocal select,pairs = select,pairs\nlocal function_arg\n\ntable.unpack = table.unpack or unpack\n\n---------------------------------------------------\n-- String utilties.\n-- @section string\n---------------------------------------------------\n\n--- split a delimited string into an array of strings.\n-- @param s The input string\n-- @param re A Lua string pattern; defaults to '%s+'\n-- @param n optional maximum number of splits\n-- @return an array of strings\nfunction ml.split(s,re,n)\n    local find,sub,append = string.find, string.sub, table.insert\n    local i1,ls = 1,{}\n    if not re then re = '%s+' end\n    if re == '' then return {s} end\n    while true do\n        local i2,i3 = find(s,re,i1)\n        if not i2 then\n            local last = sub(s,i1)\n            if last ~= '' then append(ls,last) end\n            if #ls == 1 and ls[1] == '' then\n                return {}\n            else\n                return ls\n            end\n        end\n        append(ls,sub(s,i1,i2-1))\n        if n and #ls == n then\n            ls[#ls] = sub(s,i1)\n            return ls\n        end\n        i1 = i3+1\n    end\nend\n\nml.lua51 = _VERSION:match '5%.1$'\n\n--- escape any 'magic' pattern characters in a string.\n-- Useful for functions like `string.gsub` and `string.match` which\n-- always work with Lua string patterns.\n-- For any s, `s:match('^'..escape(s)..'$') == s` is `true`.\n-- @param s The input string\n-- @return an escaped string\nfunction ml.escape(s)\n    local res = s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')\n    if ml.lua51 then\n        res = res:gsub('%z','%%z')\n    end\n    return res\nend\n\n--- expand a string containing any `${var}` or `$var`.\n-- Substitution values should be only numbers or strings.\n-- However, you should pick _either one_ consistently!\n-- @param s the string\n-- @param subst either a table or a function (as in `string.gsub`)\n-- @return expanded string\nfunction ml.expand (s,subst)\n    local res,k = s:gsub('%${([%w_]+)}',subst)\n    if k > 0 then return res end\n    return (res:gsub('%$([%w_]+)',subst))\nend\n\n--- return the contents of a file as a string\n-- @param filename The file path\n-- @param is_bin open in binary mode, default false\n-- @return file contents, or nil,error\nfunction ml.readfile(filename,is_bin)\n    local mode = is_bin and 'b' or ''\n    local f,err = io.open(filename,'r'..mode)\n    if not f then return nil,err end\n    local res,err = f:read('*a')\n    f:close()\n    if not res then return nil,err end\n    return res\nend\n\n--- write a string to a file,\n-- @param filename The file path\n-- @param str The string\n-- @param is_bin open in binary mode, default false\n-- @return true or nil,error\nfunction ml.writefile(filename,str,is_bin)\n    local f,err = io.open(filename,'w'..(is_bin or ''))\n    if not f then return nil,err end\n    f:write(str)\n    f:close()\n    return true\nend\n\n---------------------------------------------------\n-- File and Path functions\n-- @section file\n---------------------------------------------------\n\n--- Does a file exist?\n-- @param filename a file path\n-- @return the file path, otherwise nil\n-- @usage file = exists 'readme' or exists 'readme.txt' or exists 'readme.md'\nfunction ml.exists (filename)\n    local f = io.open(filename)\n    if not f then\n        return nil\n    else\n        f:close()\n        return filename\n    end\nend\n\nlocal sep, other_sep = package.config:sub(1,1),'/'\n\n--- split a path into directory and file part.\n-- if there's no directory part, the first value will be the empty string.\n-- Handles both forward and back-slashes on Windows.\n-- @param P A file path\n-- @return the directory part\n-- @return the file part\nfunction ml.splitpath(P)\n    local i = #P\n    local ch = P:sub(i,i)\n    while i > 0 and ch ~= sep and ch ~= other_sep do\n        i = i - 1\n        ch = P:sub(i,i)\n    end\n    if i == 0 then\n        return '',P\n    else\n        return P:sub(1,i-1), P:sub(i+1)\n    end\nend\n\n--- split a path into root and extension part.\n-- if there's no extension part, the second value will be empty\n-- @param P A file path\n-- @return the name part\n-- @return the extension\nfunction ml.splitext(P)\n    local i = #P\n    local ch = P:sub(i,i)\n    while i > 0 and ch ~= '.' do\n        if ch == sep or ch == other_sep then\n            return P,''\n        end\n        i = i - 1\n        ch = P:sub(i,i)\n    end\n    if i == 0 then\n        return P,''\n    else\n        return P:sub(1,i-1),P:sub(i)\n    end\nend\n\n---------------------------------------------------\n-- Extended table functions.\n-- 'array' here is shorthand for 'array-like table'; these functions\n-- only operate over the numeric `1..#t` range of a table and are\n-- particularly efficient for this purpose.\n-- @section table\n---------------------------------------------------\n\nlocal tostring = tostring -- so we can globally override tostring!\n\nlocal function quote (v)\n    if type(v) == 'string' then\n        return ('%q'):format(v)\n    else\n        return tostring(v)\n    end\nend\n\nlocal lua_keyword = {\n    [\"and\"] = true, [\"break\"] = true,  [\"do\"] = true,\n    [\"else\"] = true, [\"elseif\"] = true, [\"end\"] = true,\n    [\"false\"] = true, [\"for\"] = true, [\"function\"] = true,\n    [\"if\"] = true, [\"in\"] = true,  [\"local\"] = true, [\"nil\"] = true,\n    [\"not\"] = true, [\"or\"] = true, [\"repeat\"] = true,\n    [\"return\"] = true, [\"then\"] = true, [\"true\"] = true,\n    [\"until\"] = true,  [\"while\"] = true, [\"goto\"] = true,\n}\n\nlocal function is_iden (key)\n    return key:match '^[%a_][%w_]*$' and not lua_keyword[key]\nend\n\n\nlocal tbuff\nfunction tbuff (t,buff,k,start_indent,indent)\n    local start_indent2, indent2\n    if start_indent then\n        start_indent2 = indent\n        indent2 = indent .. indent\n    end\n    local function append (v)\n        if not v then return end\n        buff[k] = v\n        k = k + 1\n    end\n    local function put_item(value)\n        if type(value) == 'table' then\n            if not buff.tables[value] then\n                buff.tables[value] = true\n                k = tbuff(value,buff,k,start_indent2,indent2)\n            else\n                append(\"<cycle>\")\n            end\n        else\n            value = quote(value)\n            append(value)\n        end\n        append \",\"\n        if start_indent then append '\\n' end\n    end\n    append \"{\"\n    if start_indent then append '\\n' end\n    -- array part -------\n    local array = {}\n    for i,value in ipairs(t) do\n        append(indent)\n        put_item(value)\n        array[i] = true\n    end\n    -- 'map' part ------\n    for key,value in pairs(t) do if not array[key] then\n        append(indent)\n        -- non-identifiers need [\"key\"]\n        if type(key)~='string' or not is_iden(key) then\n            if type(key)=='table' then\n                key = ml.tstring(key)\n            else\n                key = quote(key)\n            end\n            key = \"[\"..key..\"]\"\n        end\n        append(key..'=')\n        put_item(value)\n    end end\n    -- removing trailing comma is done for prettiness, but this implementation\n    -- is not pretty at all!\n    local last = start_indent and buff[k-2] or buff[k-1]\n    if start_indent then\n        if last == '{' then -- empty table\n            k = k - 1\n        else\n            if last == ',' then -- get rid of trailing comma\n                k = k - 2\n                append '\\n'\n            end\n            append(start_indent)\n        end\n    elseif last == \",\" then -- get rid of trailing comma\n        k = k - 1\n    end\n    append \"}\"\n    return k\nend\n\n--- return a string representation of a Lua value.\n-- Cycles are detected, and the result can be optionally indented nicely.\n-- @param t the table\n-- @param how (optional) a table with fields `spacing' and 'indent', or a string corresponding\n-- to `indent`.\n-- @return a string\nfunction ml.tstring (t,how)\n    if type(t) == 'table' and not (getmetatable(t) and getmetatable(t).__tostring) then\n        local buff = {tables={[t]=true}}\n        how = how or {}\n        if type(how) == 'string' then how = {indent = how} end\n        pcall(tbuff,t,buff,1,how.spacing or how.indent,how.indent)\n        return table.concat(buff)\n    else\n        return quote(t)\n    end\nend\n\nlocal append = table.insert\n\n--- collect a series of values from an interator.\n-- @param ... iterator\n-- @return array-like table\n-- @usage collect(pairs(t)) is the same as keys(t)\nfunction ml.collect (...)\n    local res = {}\n    for k in ... do append(res,k) end\n    return res\nend\n\n--- collect from an interator up to a condition.\n-- If the function returns true, then collection stops.\n-- @param f predicate receiving (value,count)\n-- @param ... iterator\n-- @return array-like table\nfunction ml.collectuntil (f,...)\n    local res,i,pred = {},1,function_arg(f)\n    for k in ... do\n        if pred(k,i) then break end\n        res[i] = k\n        i = i + 1\n    end\n    return res\nend\n\n--- collect `n` values from an interator.\n-- @param n number of values to collect\n-- @param ... iterator\n-- @return array-like table\nfunction ml.collectn (n,...)\n    return collectuntil(function(k,i) return i > n end,...)\nend\n\n--- collect the second value from a iterator.\n-- If the second value is `nil`, it won't be collected!\n-- @param ... iterator\n-- @return array-like table\n-- @usage collect2nd(pairs{one=1,two=2}) is {1,2} or {2,1}\nfunction ml.collect2nd (...)\n    local res = {}\n    for _,v in ... do append(res,v) end\n    return res\nend\n\n--- extend a table by mapping a function over another table.\n-- @param dest destination table\n-- @param j start index in destination\n-- @param nilv default value to use if function returns `nil`\n-- @param f the function\n-- @param t source table\n-- @param ... extra arguments to function\nfunction ml.mapextend (dest,j,nilv,f,t,...)\n    f = function_arg(f)\n    if j == -1 then j = #dest + 1 end\n    for i = 1,#t do\n        local val = f(t[i],...)\n        val = val~=nil and val or nilv\n        if val ~= nil then\n            dest[j] = val\n            j = j + 1\n        end\n    end\n    return dest\nend\n\nlocal mapextend = ml.mapextend\n\n--- map a function over an array.\n-- The output must always be the same length as the input, so\n-- any `nil` values are mapped to `false`.\n-- @param f a function of one or more arguments\n-- @param t the array\n-- @param ... any extra arguments to the function\n-- @return a new array with elements `f(t[i],...)`\nfunction ml.imap(f,t,...)\n    return mapextend({},1,false,f,t,...)\nend\n\n--- apply a function to each element of an array.\n-- @param f a function of one or more arguments\n-- @param t the array\n-- @param ... any extra arguments to the function\n-- @return the transformed array\nfunction ml.transform (f,t,...)\n    return mapextend(t,1,false,f,t,...)\nend\n\n--- map a function over values from two arrays.\n-- Length of output is the size of the smallest array.\n-- @param f a function of two or more arguments\n-- @param t1 first array\n-- @param t2 second array\n-- @param ... any extra arguments to the function\n-- @return a new array with elements `f(t1[i],t2[i],...)`\nfunction ml.imap2(f,t1,t2,...)\n    f = function_arg(f)\n    local res = {}\n    local n = math.min(#t1,#t2)\n    for i = 1,n do\n        res[i] = f(t1[i],t2[i],...) or false\n    end\n    return res\nend\n\n--- map a function over an array only keeping non-`nil` values.\n-- @param f a function of one or more arguments\n-- @param t the array\n-- @param ... any extra arguments to the function\n-- @return a new array with elements `v = f(t[i],...) such that v ~= nil`\nfunction ml.imapfilter (f,t,...)\n    return mapextend({},1,nil,f,t,...)\nend\n\n--- filter an array using a predicate.\n-- @param t a table\n-- @param pred a function that must return `nil` or `false`\n-- to exclude a value\n-- @param ... any extra arguments to the predicate\n-- @return a new array such that `pred(t[i])` evaluates as true\nfunction ml.ifilter(t,pred,...)\n    local res,k = {},1\n    pred = function_arg(pred)\n    for i = 1,#t do\n        if pred(t[i],...) then\n            res[k] = t[i]\n            k = k + 1\n        end\n    end\n    return res\nend\n\n--- find an item in an array using a predicate.\n-- @param t the array\n-- @param pred a function of at least one argument\n-- @param ... any extra arguments\n-- @return the item value, or `nil`\n-- @usage ifind({{1,2},{4,5}},'X[1]==Y',4) is {4,5}\nfunction ml.ifind(t,pred,...)\n    pred = function_arg(pred)\n    for i = 1,#t do\n        if pred(t[i],...) then\n            return t[i]\n        end\n    end\nend\n\n--- return the index of an item in an array.\n-- @param t the array\n-- @param value item value\n-- @param cmp optional comparison function (default is `X==Y`)\n-- @return index, otherwise `nil`\nfunction ml.indexof (t,value,cmp)\n    if cmp then cmp = function_arg(cmp) end\n    for i = 1,#t do\n        local v = t[i]\n        if cmp and cmp(v,value) or v == value then\n            return i\n        end\n    end\nend\n\nlocal function upper (t,i2)\n    if not i2 or i2 > #t then\n        return #t\n    elseif i2 < 0 then\n        return #t + i2 + 1\n    else\n        return i2\n    end\nend\n\nlocal function copy_range (dest,index,src,i1,i2)\n    local k = index\n    for i = i1,i2 do\n        dest[k] = src[i]\n        k = k + 1\n    end\n    return dest\nend\n\n--- return a slice of an array.\n-- Like `string.sub`, the end index may be negative.\n-- @param t the array\n-- @param i1 the start index, default 1\n-- @param i2 the end index, default #t\n-- @return an array of `t[i]` for `i` from `i1` to `i2` inclusive\nfunction ml.sub(t,i1,i2)\n    i1, i2 = i1 or 1, upper(t,i2)\n    return copy_range({},1,t,i1,i2)\nend\n\n--- delete a range of values from an array.\n-- @param tbl the array\n-- @param start start index\n-- @param finish end index (like `ml.sub`)\nfunction ml.removerange(tbl,start,finish)\n    finish = upper(tbl,finish)\n    local count = finish - start + 1\n    for k=start+count,#tbl do tbl[k-count]=tbl[k] end\n    for k=#tbl,#tbl-count+1,-1 do tbl[k]=nil end\nend\n\n--- copy values from `src` into `dest` starting at `index`.\n-- By default, it moves up elements of `dest` to make room.\n-- @param dest destination array\n-- @param index start index in destination\n-- @param src source array\n-- @param overwrite write over values\nfunction ml.insertvalues(dest,index,src,overwrite)\n    local sz = #src\n    if not overwrite then\n        for i = #dest,index,-1 do dest[i+sz] = dest[i] end\n    end\n    copy_range(dest,index,src,1,sz)\nend\n\n--- extend an array using values from other tables.\n-- @{readme.md.Extracting_and_Mapping}\n-- @param t the array to be extended\n-- @param ... the other arrays\n-- @return the extended array\nfunction ml.extend(t,...)\n    for i = 1,select('#',...) do\n        ml.insertvalues(t,#t+1,select(i,...),true)\n    end\n    return t\nend\n\n--- make an array of indexed values.\n-- Generalized table indexing. Result will only contain\n-- values for keys that exist.\n-- @param t a table\n-- @param keys an array of keys or indices\n-- @return an array `L` such that `L[keys[i]]`\n-- @usage indexby({one=1,two=2},{'one','three'}) is {1}\n-- @usage indexby({10,20,30,40},{2,4}) is {20,40}\nfunction ml.indexby(t,keys)\n    local res = {}\n    for _,v in pairs(keys) do\n        if t[v] ~= nil then\n            append(res,t[v])\n        end\n    end\n    return res\nend\n\n--- create an array of numbers from start to end.\n-- With one argument it goes `1..x1`. `d` may be a\n-- floating-point fraction\n-- @param x1 start value\n-- @param x2 end value\n-- @param d increment (default 1)\n-- @return array of numbers\n-- @usage range(2,10) is {2,3,4,5,6,7,8,9,10}\n-- @usage range(5) is {1,2,3,4,5}\nfunction ml.range (x1,x2,d)\n    if not x2 then\n        x2 = x1\n        x1 = 1\n    end\n    d = d or 1\n    local res,k = {},1\n    for x = x1,x2,d do\n        res[k] = x\n        k = k + 1\n    end\n    return res\nend\n\n-- Bring modules or tables into 't`.\n-- If `lib` is a string, then it becomes the result of `require`\n-- With only one argument, the second argument is assumed to be\n-- the `ml` table itself.\n-- @param t table to be updated, or current environment\n-- @param lib table, module name or `nil` for importing 'ml'\n-- @return the updated table\nfunction ml.import(t,...)\n    local other\n    -- explicit table, or current environment\n    -- this isn't quite right - we won't get the calling module's _ENV\n    -- this way. But it does prevent execution of the not-implemented setfenv.\n    t = t or _ENV or getfenv(2)\n    local libs = {}\n    if select('#',...)==0 then -- default is to pull in this library!\n        libs[1] = ml\n    else\n        for i = 1,select('#',...) do\n            local lib = select(i,...)\n            if type(lib) == 'string' then\n                local value = _G[lib]\n                if not value then -- lazy require!\n                    value = require (lib)\n                    -- and use the module part of package for the key\n                    lib = lib:match '[%w_]+$'\n                end\n                lib = {[lib]=value}\n            end\n            libs[i] = lib\n        end\n    end\n    return ml.update(t,table.unpack(libs))\nend\n\n--- add the key/value pairs of arrays to the first array.\n-- For sets, this is their union. For the same keys,\n-- the values from the first table will be overwritten.\n-- @param t table to be updated\n-- @param ... tables containg more pairs to be added\n-- @return the updated table\nfunction ml.update (t,...)\n    for i = 1,select('#',...) do\n        for k,v in pairs(select(i,...)) do\n            t[k] = v\n        end\n    end\n    return t\nend\n\n--- make a table from an array of keys and an array of values.\n-- @param t an array of keys\n-- @param tv an array of values\n-- @return a table where `{[t[i]]=tv[i]}`\n-- @usage makemap({'power','glory'},{20,30}) is {power=20,glory=30}\nfunction ml.makemap(t,tv)\n    local res = {}\n    for i = 1,#t do\n        res[t[i]] = tv and tv[i] or i\n    end\n    return res\nend\n\n--- make a set from an array.\n-- The values are the original array indices.\n-- @param t an array of values\n-- @return a table where the keys are the indices in the array.\n-- @usage invert{'one','two'} is {one=1,two=2}\n-- @function ml.invert\nml.invert = ml.makemap\n\n--- extract the keys of a table as an array.\n-- @param t a table\n-- @return an array of keys\nfunction ml.keys(t)\n    return ml.collect(pairs(t))\nend\n\n--- are all the values of `other` in `t`?\n-- @param t a set\n-- @param other a possible subset\n-- @treturn bool\nfunction ml.issubset(t,other)\n    for k,v in pairs(other) do\n        if t[k] == nil then return false end\n    end\n    return true\nend\n\n--- are all the keys of `other` in `t`?\n-- @param t a table\n-- @param other another table\n-- @treturn bool\nml.containskeys = ml.issubset\n\n--- return the number of keys in this table, or members in this set.\n-- @param t a table\n-- @treturn int key count\nfunction ml.count (t)\n    local count = 0\n    for k in pairs(t) do count = count + 1 end\n    return count\nend\n\n--- do these tables have the same keys?\n-- THis is set equality.\n-- @param t a table\n-- @param other a table\n-- @return true or false\nfunction ml.equalkeys(t,other)\n    return ml.issubset(t,other) and ml.issubset(other,t)\nend\n\n---------------------------------------------------\n-- Functional helpers.\n-- @section function\n---------------------------------------------------\n\n--- create a function which will throw an error on failure.\n-- @param f a function that returns nil,err if it fails\n-- @return an equivalent function that raises an error\nfunction ml.throw(f)\n    f = function_arg(f)\n    return function(...)\n        local r1,r2,r3 = f(...)\n        if not r1 then error(r2,2) end\n        return r1,r2,r3\n    end\nend\n\n--- bind the value `v` to the first argument of function `f`.\n-- @param f a function of at least one argument\n-- @param v a value\n-- @return a function of one less argument\n-- @usage (bind1(string.match,'hello')('^hell') == 'hell'\nfunction ml.bind1(f,v)\n    f = function_arg(f)\n    return function(...)\n        return f(v,...)\n    end\nend\n\n--- bind the value `v` to the second argument of function `f`.\n-- @param f a function of at least one argument\n-- @param v a value\n-- @return a function of one less argument\n-- @usage (bind2(string.match,'^hell')('hello') == 'hell'\nfunction ml.bind2(f,v)\n    f = function_arg(f)\n    return function(x,...)\n        return f(x,v,...)\n    end\nend\n\n--- compose two functions.\n-- For instance, `printf` can be defined as `compose(io.write,string.format)`\n-- @param f1 a function\n-- @param f2 a function\n-- @return `f1(f2(...))`\nfunction ml.compose(f1,f2)\n    f1 = function_arg(f1)\n    f2 = function_arg(f2)\n    return function(...)\n        return f1(f2(...))\n    end\nend\n\n--- a function returning the second value of `f`\n-- @param f a function returning at least two values\n-- @return a function returning second of those values\n-- @usage take2(splitpath) is basename\nfunction ml.take2 (f)\n    f = function_arg(f)\n    return function(...)\n        local _,b = f(...)\n        return b\n    end\nend\n\n--- is the object either a function or a callable object?.\n-- @param obj Object to check.\n-- @return true if callable\nfunction ml.callable (obj)\n    return type(obj) == 'function' or getmetatable(obj) and getmetatable(obj).__call\nend\n\n--- create a callable from an indexable object.\n-- @param t a table or other indexable object.\nfunction ml.map2fun (t)\n    return setmetatable({},{\n        __call = function(obj,key) return t[key] end\n    })\nend\n\n--- create an indexable object from a callable.\n-- @param f a callable of one argument.\nfunction ml.fun2map (f)\n    return setmetatable({},{\n        __index = function(obj,key) return f(key) end;\n        __newindex = function() error(\"not writeable!\",2) end\n    })\nend\n\nlocal function _string_lambda (f)\n    local code = 'return function(X,Y,Z) return '..f..' end'\n    local chunk = assert(loadstring(code,'tmp'))\n    return chunk()\nend\n\nlocal string_lambda\n\n--- defines how we convert something to a callable.\n--\n-- Currently, anything that matches @{callable} or is a _string lambda_.\n-- These are expressions with any of the placeholders, `X`,`Y` or `Z`\n-- corresponding to the first, second or third argument to the function.\n--\n-- This can be overriden by people\n-- wishing to extend the idea of 'callable' in this library.\n-- @param f a callable or a string lambda.\n-- @return a function\n-- @raise error if `f` is not callable in any way, or errors in string lambda.\n-- @usage function_arg('X+Y')(1,2) == 3\nfunction ml.function_arg(f)\n    if type(f) == 'string' then\n        if not string_lambda then\n            string_lambda = ml.memoize(_string_lambda)\n        end\n        f = string_lambda(f)\n    else\n        assert(ml.callable(f),\"expecting a function or callable object\")\n    end\n    return f\nend\n\nfunction_arg = ml.function_arg\n\n--- 'memoize' a function (cache returned value for next call).\n-- This is useful if you have a function which is relatively expensive,\n-- but you don't know in advance what values will be required, so\n-- building a table upfront is wasteful/impossible.\n-- @param func a function of at least one argument\n-- @return a function with at least one argument, which is used as the key.\nfunction ml.memoize(func)\n    return setmetatable({}, {\n        __index = function(self, k, ...)\n            local v = func(k,...)\n            self[k] = v\n            return v\n        end,\n        __call = function(self, k) return self[k] end\n    })\nend\n\n---------------------------------------------------\n-- Classes.\n-- @section class\n---------------------------------------------------\n\n--- create a class with an optional base class.\n--\n-- See  @{readme.md.Classes}\n-- The resulting table can be called to make a new object, which invokes\n-- an optional constructor named `_init`. If the base\n-- class has a constructor, you can call it as the `super()` method.\n-- Every class has a `_class` and a maybe-nil `_base` field, which can\n-- be accessed through the object.\n--\n-- All metamethods are inherited.\n-- The class is given a function `Klass.classof(obj)`.\n-- @param base optional base class\n-- @return the callable metatable representing the class\nfunction ml.class(base)\n    local klass, base_ctor = {}\n    if base then\n        ml.import(klass,base)\n        klass._base = base\n        base_ctor = rawget(base,'_init')\n    end\n    klass.__index = klass\n    klass._class = klass\n    klass.classof = function(obj)\n        local m = getmetatable(obj) -- an object created by class() ?\n        if not m or not m._class then return false end\n        while m do -- follow the inheritance chain --\n            if m == klass then return true end\n            m = rawget(m,'_base')\n        end\n        return false\n    end\n    setmetatable(klass,{\n        __call = function(klass,...)\n            local obj = setmetatable({},klass)\n            if rawget(klass,'_init') then\n                klass.super = base_ctor\n                local res = klass._init(obj,...) -- call our constructor\n                if res then -- which can return a new self..\n                    obj = setmetatable(res,klass)\n                end\n            elseif base_ctor then -- call base ctor automatically\n                base_ctor(obj,...)\n            end\n            return obj\n        end\n    })\n    return klass\nend\n\n------------------------\n-- a simple Array class.\n-- @{readme.md.Array_Class}\n--\n-- `table` functions: `sort`,`concat`,`insert`,`remove`,`insert` as `append`.\n--\n-- `ml` functions: `ifilter` as `filter`,`imap` as `map`,`sub`,`indexby`,`range`,\n-- `indexof`,`ifind` as `find`,`extend`,`split` and `collect`.\n--\n-- The `sorted` method returns a sorted copy.\n--\n-- Concatenation, equality and custom tostring is defined.\n--\n-- This implementation has covariant methods; so that methods like `map` and `sub`\n-- will return an object of the derived type, not `Array`\n-- @table Array\n\nlocal Array\n\nif not rawget(_G,'NO_MICROLIGHT_ARRAY') then\n\n    Array = ml.class()\n\n    local extend, setmetatable, C = ml.extend, setmetatable, ml.compose\n\n    local function set_class (self,res)\n        return setmetatable(res,self._class)\n    end\n\n    local function awrap (fun)\n        return function(self,...) return set_class(self,fun(self,...))  end\n    end\n\n    local function awraps (fun)\n        return function(self,f,...) return set_class(self,fun(f,self,...))  end\n    end\n\n    -- a class is just a table of functions, so we can do wholesale updates!\n    ml.import(Array,{\n        -- straight from the table library\n        concat=table.concat,insert=table.insert,remove=table.remove,append=table.insert,\n        -- originals return table; these versions make the tables into arrays.\n        filter=awrap(ml.ifilter),sub=awrap(ml.sub), indexby=awrap(ml.indexby),\n        map=awraps(ml.imap), map2=awraps(ml.imap2), mapfilter=awraps(ml.imapfilter),\n        range=C(Array,ml.range),split=C(Array,ml.split),collect=C(Array,ml.collect),\n        indexof=ml.indexof, find=ml.ifind, extend=ml.extend\n    })\n\n    -- A constructor can return a _specific_ object\n    function Array:_init(t)\n        if not t then return nil end  -- no table, make a new one\n        if t._class == self._class then  -- was already a Array: copy constructor!\n            t = ml.sub(t,1)\n        end\n        return t\n    end\n\n    function Array:sort(f)\n        if type(f) ~= \"nil\" then f = function_arg(f) end\n        table.sort(self,f)\n        return self\n    end\n\n    function Array:sorted(f)\n        return self:sub(1):sort(f)\n    end\n\n    function Array:foreach(f,...)\n        f = function_arg(f)\n        for i = 1,#self do f(self[i],...) end\n    end\n\n    function Array.mappers (klass,t)\n        local method = Array.mapfilter\n        if t.__use then\n            method = t.__use\n            t.__use = nil\n        end\n        for k,f in pairs(t) do\n            klass[k] = ml.bind2(method,function_arg(f))\n        end\n    end\n\n    function Array:__tostring()\n        return '{' .. self:map(ml.tstring):concat ',' .. '}'\n    end\n\n    function Array.__eq(l1,l2)\n        if #l1 ~= #l2 then return false end\n        for i = 1,#l1 do\n            if l1[i] ~= l2[i] then return false end\n        end\n        return true\n    end\n\n    function Array.__concat (l1,l2)\n        return set_class(l1,extend({},l1,l2))\n    end\n\nend\n\nml.Array = Array\n\nreturn ml\n"
  },
  {
    "path": "ml_module.lua",
    "content": "---------\n-- Simple Lua 5.2 module.\n-- Thin wrapper around ml.import\n--\n--    local _ENV = require 'ml_module' (_G)\n--    function f1() .. end\n--    function f2() .. end\n--    return _M\n--\n-- See mod52.lua for an example of usage\n-- @module ml_module\n\nlocal ml = require 'ml'\n\nreturn function(G,...)\n    local _M, EMT = {}, {}\n    local env = {_M=_M}  --> this will become _ENV\n\n    ml.import(env,...)\n\n    EMT.__newindex = function(t,k,v)\n        rawset(env,k,v)  -- copy to environment\n        _M[k] = v        -- and add to module!\n    end\n\n    -- any undefined lookup goes to 'global' table specified\n    if G ~= nil then EMT.__index = G  end\n\n    return setmetatable(env,EMT)\nend\n"
  },
  {
    "path": "ml_properties.lua",
    "content": "--- set properties table for an existing class.\n-- A property P can be fully specified by the class having\n-- 'get_P' and 'set_P' methods. If only the setter is specified,\n-- then accessing P acesses a private variable '_P'. If no\n-- setters are specified, then the class can be notified of any\n-- changes by defining an update() method and setting the special field\n-- `__update` of `props` to that method.\n-- `klass` is a class generated by 'ml.class`\n-- `props` property definitions. This assigns each property\n-- to a default value.\n-- @module ml_properties\n\nlocal ml = require 'ml'\n\nreturn function (klass,props)\n    local setters,getters,_props,_names,_defs = {},{},{},{},{}\n    local rawget = rawget\n\n    local update = props.__update\n    props.__update = nil\n    for k,t in pairs(props) do\n        getters[k] = rawget(klass,'get_'..k)\n        if not getters[k] then\n            _props['_'..k] = t\n            _names[k] = '_'..k\n        end\n        setters[k] = rawget(klass,'set_'..k)\n        if setters[k] then\n            _defs[k] = t\n        end\n    end\n    klass._props = props\n\n    -- patch the constructor so it sets property default values\n    local kmt = getmetatable(klass)\n    local ctor = kmt.__call\n    kmt.__call = function(...)\n        local newi = klass.__newindex\n        klass.__newindex = nil\n        local obj = ctor(...)\n        ml.import(obj,_props)\n        for k,set in pairs(setters) do\n            set(obj,_defs[k])\n        end\n        klass.__newindex = newi\n        return obj\n    end\n\n    klass.__index = function(t,k)\n        local v = rawget(klass,k)\n        if v then return v end\n        local getter = getters[k]\n        if getter then\n            return getter(t,k)\n        else\n            local _name = _names[k]\n            if _name then return t[_name]\n            else error(\"unknown readable property: \"..k,2)\n            end\n        end\n    end\n\n    klass.__newindex = function(t,k,v)\n        local setter = setters[k]\n        if setter then\n            setter(t,v,k)\n        else\n            local _name = _names[k]\n            if _name then\n                t[_name] = v\n                if update then update(t,k,v) end\n            else error(\"unknown writeable property: \"..k,2)\n            end\n        end\n    end\nend\n"
  },
  {
    "path": "ml_range.lua",
    "content": "-- ml_range.lua (c) 2012 Dirk Laurie, Lua-like MIT licence, except that\n--    Steve Donovan is allowed to use the code in any way he likes.\n\n--[[\nUsage:\n\n    range = require \"ml_range\"\n\n `range(n)` returns {1,2,3,...,n}, with vector semantics. All binary\n operations are term-by-term, with numbers allowed left or right.\n Exponentiation and logical operators are undefined at this stage.\n Sum and product methods, with optional starting values, are supplied.\n\n The vector class could be useful independently. To gain access to it:\n    Vector = getmetatable(range(1))\n Then e.g. Vector{1,2,3,4} creates a vector.\n\n Some fun can be had with\n     debug.setmetatable(1,{__len=range})\n e.g.\n    print(2*#10-1) --> {1,3,5,7,9,11,13,15,17,19}\n]]\n\nlocal concat = table.concat\nlocal isnumber = function(x) return type(x)=='number' end\nlocal instance = function (class,obj) return setmetatable(obj,class) end\n\nlocal Vector\nVector = {\n    __unm = function(x) local s=Vector{}\n       for k=1,#x do s[k]=-x[k] end\n       return s\n    end;\n    __add = function(x,y) local s=Vector{}\n       if isnumber(x) then for k=1,#y do s[k]=x+y[k] end\n          elseif isnumber(y) then for k=1,#x do s[k]=x[k]+y end\n          else for k=1,#x do s[k]=x[k]+y[k] end\n          end\n       return s\n    end;\n    __sub = function(x,y) local s=Vector{}\n       if isnumber(x) then for k=1,#y do s[k]=x-y[k] end\n          elseif isnumber(y) then for k=1,#x do s[k]=x[k]-y end\n          else for k=1,#x do s[k]=x[k]-y[k] end\n          end\n       return s\n    end;\n    __mul = function(x,y) local s=Vector{}\n       if isnumber(x) then for k=1,#y do s[k]=x*y[k] end\n          elseif isnumber(y) then for k=1,#x do s[k]=x[k]*y end\n          else for k=1,#x do s[k]=x[k]*y[k] end\n          end\n       return s\n    end;\n    __div = function(x,y) local s=Vector{}\n       if isnumber(x) then for k=1,#y do s[k]=x/y[k] end\n          elseif isnumber(y) then for k=1,#x do s[k]=x[k]/y end\n          else for k=1,#x do s[k]=x[k]/y[k] end\n          end\n       return s\n    end;\n    __concat = function(x,y) local s=Vector{}\n       for k,v in ipairs(x) do s[k]=v end\n       if isnumber(x) then insert(s,1,x)\n          elseif isnumber(y) then append(s,x)\n          else for k,v in ipairs(y) do s[#s+1]=v end\n          end\n       return s\n    end;\n    __tostring = function(x) return '{'..concat(x,',')..'}'\n    end;\n    sum = function(x,y) local sum=y or 0\n       for k,v in ipairs(x) do sum = sum+v end\n       return sum\n    end;\n    prod = function(x,y) local prod=y or 1\n       for k,v in ipairs(x) do prod = prod*v end\n       return prod\n    end;\n}\nsetmetatable(Vector,{__call = instance})\nVector.__index = Vector\n\nlocal function range(x)\n   local s=Vector{}\n   for k=1,x do s[k]=k end\n   return s\nend\n\nreturn range\n"
  },
  {
    "path": "mod52.lua",
    "content": "\nlocal _ENV = require 'ml_module' (nil, -- no wholesale access to _G\n    'print','assert','os', -- quoted global values brought in\n    'lfs', -- not global, so use require()!\n    table -- not quoted, import the whole table into the environment!\n    )\n\nfunction format (s)\n    local out = {'Hello',s,'at',os.date('%c'),'here is',lfs.currentdir()}\n    return concat(out,' ')\nend\n\nfunction message(s)\n    print(format(s))\nend\n\n-- no, we didn't bring anything else in\nassert(setmetatable == nil)\n\n-- NB return the _module_, not the _environment_!\nreturn _M\n"
  },
  {
    "path": "readme.md",
    "content": "# A Small but Useful Lua library\n\nThe Lua standard library is deliberately kept small, based on the abstract platform\ndefined by the C89 standard. It is intended as a base for further development, so Lua\nprogrammers tend to collect small useful functions for their projects.\n\nMicrolight is an attempt at 'library golf', by analogy to the popular nerd sport 'code\ngolf'. The idea here is to try capture some of these functions in one place and document\nthem well enough so that it is easier to use them than to write them yourself.\n\nThis library is intended to be a 'extra light' version of Penlight, which has nearly two\ndozen modules and hundreds of functions.\n\nIn Lua, anything beyond the core involves 'personal' choice, and this list of functions\ndoes not claim to aspire to 'canonical' status. It emerged from discussion on the Lua\nMailing list started by Jay Carlson, and was implemented by myself and Dirk Laurie.\n\n## Strings\n\nTHere is no built-in way to show a text representation of a Lua table, which can be\nfrustrating for people first using the interactive prompt. Microlight provides `tstring`.\nPlease note that globally redefining `tostring` is _not_ a good idea for Lua application\ndevelopment! This trick is intended to make experimation more satisfying:\n\n    > require 'ml'.import()\n    > tostring = tstring\n    > = {10,20,name='joe'}\n    {10,20,name=\"joe\"}\n\nThe Lua string functions are particularly powerful but there are some common functions\nmissing that tend to come up in projects frequently. There is `table.concat` for building\na string out of a table, but no `table.split` to break a string into a table.\n\n    >  = split('hello dolly')\n    {\"hello\",\"dolly\"}\n    > = split('one,two',',')\n    {\"one\",\"two\"}\n\nThe second argument is a _string pattern_ that defaults to spaces.\n\nAlthough it's not difficult to do [string\ninterpolation](http://lua-users.org/wiki/StringInterpolation) in Lua, there's no little\nfunction to do it directly. So Microlight provides `ml.expand`.\n\n    > = expand(\"hello $you, from $me\",{you='dolly',me='joe'})\n    hello dolly, from joe\n\n`expand` also understands the alternative `${var}` and may also be given a function, just\nlike `string.gsub`. (But pick one _or_ the other consistently.)\n\nLua string functions match using string patterns, which are a powerful subset of proper\nregular expressions: they contain 'magic' characters like '.','$' etc which you need to\nescape before using. `escape` is used when you wish to match a string literally:\n\n    > = ('woo%'):gsub(escape('%'),'hoo')\n    \"woohoo\"   1\n    > = split(\"1.2.3\",escape(\".\"))\n    {\"1\",\"2\",\"3\"}\n\n## Files and Paths\n\nAlthough `access` is available on most platforms, it's not part of the standard, (which\nis why it's spelt `_access` on Windows). So to test for the existance of a file, you need\nto attempt to open it. So the `exist` function is easy to write:\n\n    function ml.exists (filename)\n        local f = io.open(filename)\n        if not f then\n            return nil\n        else\n            f:close()\n            return filename\n        end\n    end\n\nThe return value is _not_ a simple true or false; it returns the filename if it exists so\nwe can easily find an existing file out of a group of candidates:\n\n    > = exists 'README' or exists 'readme.txt' or exists 'readme.md'\n    \"readme.md\"\n\nLua is good at slicing and dicing text, so a common strategy is to read all of a\nnot-so-big file and process the string. This is the job of `readfile`. For instance, this\nreturns the first 128 bytes of the file opened in binary mode:\n\n    > txt = readfile('readme.md',true):sub(1,128)\n\nNote I said bytes, not characters, since strings can contain any byte sequence.\n\nIf `readfile` can't open a file, or can't read from it, it will return `nil` and an error\nmessage. This is the pattern followed by `io.open` and many other Lua functions; it is\nconsidered bad form to raise an error for a _routine_ problem.\n\nBreaking up paths into their components is done with `splitpath` and `splitext`:\n\n    > = splitpath(path)\n    \"/path/to/dogs\" \"bonzo.txt\"\n    > = splitext(path)\n    \"/path/to/dogs/bonzo\"   \".txt\"\n    > = splitpath 'frodo.txt'\n    \"\"      \"frodo.txt\"\n    > = splitpath '/usr/'\n    \"/usr\"  \"\"\n    > = splitext '/usr/bin/lua'\n    \"/usr/bin/lua\"  \"\"\n    >\n\nThese functions return _two_ strings, one of which may be the empty string (rather than\n`nil`). On Windows, they use both forward- and back-slashes, on Unix only forward slashes.\n\n## Inserting and Extending\n\nMost of the Microlight functions work on Lua tables. Although these may be _both_ arrays\n_and_ hashmaps, generally we tend to _use_ them as one or the other. From now on, we'll\nuse array and map as shorthand terms for tables\n\n`update` adds key/value pairs to a map, and `extend` appends an array to an array; they\nare two complementary ways to add multiple items to a table in a single operation.\n\n    > a = {one=1,two=2}\n    > update(a,{three=3,four=4})\n    > = a\n    {one=1,four=4,three=3,two=2}\n    > t = {10,20,30}\n    > extend(t,{40,50})\n    > = t\n    {10,20,30,40,50}\n\nAs from version 1.1, both of these functions take an arbitrary number of tables.\n\nTo 'flatten' a table, just unpack it and use `extend`:\n\n    > pair = {{1,2},{3,4}}\n    > = extend({},unpack(pair))\n    {1,2,3,4}\n\n`extend({},t)` would just be a shallow copy of a table.\n\nMore precisely, `extend` takes an indexable and writeable object, where the index\nruns from 1 to `#O` with no holes, and starts adding new elements at `O[#O+1]`.\nSimularly, the other arguments are indexable but need not be writeable. These objects\nare typically tables, but don't need to be. You can exploit the guarantee that `extend`\nalways goes sequentially from 1 to `#T`, and make the first argument an object:\n\n    > obj = setmetatable({},{ __newindex = function(t,k,v) print(v) end })\n    > extend(obj,{1,2,3})\n    1\n    2\n    3\n\nTo insert multiple values into a position within an array, use `insertvalues`. It works\nlike `table.insert`, except that the third argument is an array of values. If you do want\nto overwrite values, then use `true` for the fourth argument:\n\n    > t = {10,20,30,40,50}\n    > insertvalues(t,2,{11,12})\n    > = t\n    {10,11,12,20,30,40,50}\n    > insertvalues(t,3,{2,3},true)\n    > = t\n    {10,11,2,3,30,40,50}\n\n(Please note that the _original_ table is modified by these functions.)\n\n`update' works like `extend`. except that all the key value pairs from the input tables\nare copied into the first argument. Keys may be overwritten by subsequent tables.\n\n    > t = {}\n    > update(t,{one=1},{ein=1},{one='ONE'})\n    > = t\n    {one=\"ONE\",ein=1}\n\n`import` is a specialized version of `update`; if the first argument is `nil` then it's\nassumed to be the global table. If no tables are provided, it brings in the ml table\nitself (hence the lazy `require \"ml\".import()` idiom).\n\nIf the arguments are strings, then we try to `require` them.  So this brings in\nLuaFileSystem and imports `lfs` into the global table. So it's a lazy way to do a whole\nbunch of requires. A module 'package.mod' will be brought in as `mod`. Note that the\nsecond form actually does bring all of `lpeg`'s functions in.\n\n    > import(nil,'lfs')\n    > import(nil,require 'lpeg')\n\n\n## Extracting and Mapping\n\nThe opposite operation to extending is extracting a number of items from a table.\n\nThere's `sub`, which works just like `string.sub` and is the equivalent of list slicing\nin Python:\n\n    > numbers = {10,20,30,40,50}\n    > = sub(numbers,1,1)\n    {10}\n    > = sub(numbers,2)\n    {20,30,40,50}\n    > = sub(numbers,1,-2)\n    {10,20,30,40}\n\n`indexby` indexes a table by an array of keys:\n\n    > = indexby(numbers,{1,4})\n    {10,40}\n    > = indexby({one=1,two=2,three=3},{'three','two'})\n    {[3,2}\n\nHere is the old standby `imap`, which makes a _new_ array by applying a function to the\noriginal elements:\n\n    > words = {'one','two','three'}\n    > = imap(string.upper,words)\n    {\"ONE\",\"TWO\",\"THREE\"}\n    > s = {'10','x','20'}\n    > ns = imap(tonumber,s)\n    > = ns\n    {10,false,20}\n\n`imap` must always return an array of the same size - if the function returns `nil`, then\nwe avoid leaving a hole in the array by using `false` as a placeholder.\n\nAnother popular function `indexof` does a linear search for a value and returns the\n1-based index, or `nil` if not successful:\n\n    > = indexof(numbers,20)\n    2\n    > = indexof(numbers,234)\n    nil\n\nThis function takes an optional third argument, which is a custom equality function.\n\nIn general, you want to match something more than just equality. `ifind` will return the\nfirst value that satisfies the given function.\n\n    > s = {'x','10','20','y'}\n    > = ifind(s,tonumber)\n    \"10\"\n\nThe standard function `tonumber` returns a non-nil value, so the corresponding value is\nreturned - that is, the string. To get all the values that match, use `ifilter`:\n\n    > = ifilter(numbers,tonumber)\n    {\"10\",\"20\"}\n\nThere is a useful hybrid between `imap` and `ifilter` called `imapfilter` which is\nparticularly suited to Lua use, where a function commonly returns either something useful,\nor nothing. (Phillip Janda originally suggested calling this `transmogrify`, since\nno-one has preconceptions about it, except that it's a cool toy for imaginative boys).\n\n    > = imapfilter(tonumber,{'one',1,'f',23,2})\n    {1,23,2}\n\n`collect` makes a array out of an iterator. 'collectuntil` can be given a\ncustom predicate and `collectn` takes up to a maximum number of values,\nwhich is useful for iterators that never terminate.\n(Note that we need to pass it either a proper iterator, like `pairs`, or\na function or exactly one function - which isn't the case with `math.random`)\n\n    > s = 'my dog ate your homework'\n    > words = collect(s:gmatch '%a+')\n    > = words\n    {\"my\",\"dog\",\"ate\",\"your\",\"homework\"}\n    > R = function() return math.random() end\n    > = collectn(3,R)\n    {0.0012512588885159,0.56358531449324,0.19330423902097}\n    > lines = collectuntil(4,io.lines())\n    one\n    two\n    three\n    four\n    > = lines\n    {\"one\",\"two\",\"three\",\"four\"}\n\nA simple utility to sort standard input looks like this:\n\n    require 'ml'.import()\n    lines = collect(io.lines())\n    table.sort(lines)\n    print(table.concat(lines,'\\n'))\n\nAnother standard function that can be used here is `string.gmatch`.\n\nLuaFileSystem defines an iterator over directory contents. `collect(lfs.dir(D))` gives\nyou an _array_ of all files in directory `D`.\n\nFinally, `removerange` removes a _range_ of values from an array, and takes the same\narguments as `sub`. Unlike the filters filters, it works in-place.\n\n## Sets and Maps\n\n`indexof` is not going to be your tool of choice for really big tables, since it does a\nlinear search. Lookup on Lua hash tables is faster, if we can get the data into the right\nshape.  `invert` turns a array of values into a table with those values as keys:\n\n    > m = invert(numbers)\n    > = m\n    {[20]=2,[10]=1,[40]=4,[30]=3,[50]=5}\n    > = m[20]\n    2\n    > = m[30]\n    3\n    > = m[25]\n    nil\n    > m = invert(words)\n    > = m\n    {one=1,three=3,two=2}\n\nSo from a array we get a reverse lookup map. This is also exactly what we want from a\n_set_: fast membership test and unique values.\n\nSets don't particularly care about the actual value, as long as it evaluates as true or\nfalse, hence:\n\n    > = issubset(m,{one=true,two=true})\n    true\n\n `makemap` takes another argument and makes up a table where the keys come from the first\narray and the values from the second array:\n\n    > = makemap({'a','b','c'},{1,2,3})\n    {a=1,c=3,b=2}\n\n\n# Higher-order Functions\n\nFunctions are first-class values in Lua, so functions may manipulate them, often called\n'higher-order' functions.\n\nBy _callable_ we either mean a function or an object which has a `__call` metamethod. The\n`callable` function checks for this case.\n\nFunction _composition_ is often useful:\n\n    > printf = compose(io.write,string.format)\n    > printf(\"the answer is %d\\n\",42)\n    the answer is 42\n\n`bind1` and `bind2` specialize functions by creating a version that has one less\nargument. `bind1` gives a function where the first argument is _bound_ to some value.\nThis can be used to pass methods to functions expecting a plain function. In Lua,\n`obj:f()` is shorthand for `obj.f(obj,...)`. Just using a dot is not enough, since there\nis no _implicit binding_ of the self argument. This is precisely what `bind1` can do:\n\n    > ewrite = bind1(io.stderr.write,io.stderr)\n    > ewrite 'hello\\n'\n\nWe want a logging function that writes a message to standard error with a line feed; just\nbind the second argument to '\\n':\n\n    > log = bind2(ewrite,'\\n')\n    > log 'hello'\n    hello\n\nNote that `sub(t,1)` does a simple array copy:\n\n    > copy = bind2(sub,1)\n    > t = {1,2,3}\n    > = copy(t)\n    {1,2,3}\n\nIt's easy to make a 'predicate' for detecting empty or blank strings:\n\n    > blank = bind2(string.match,'^%s*$')\n    > = blank ''\n    \"\"\n    > = blank '  '\n    \"  \"\n    > = blank 'oy vey'\n    nil\n\nI put 'predicate' in quotes because it's again not classic true/false; Lua actually only\ndeveloped `false` fairly late in its career. Operationally, this is a fine predicate\nbecause `nil` matches as 'false' and any string matches as 'true'.\n\nThis pattern generates a whole family of classification functions, e.g. `hex` (using\n'%x+'), `upcase` ('%u+'), `iden` ('%a[%w_]*') and so forth. You can keep the binding game\ngoing (after all, `bind2` is just a function like any other.)\n\n    > matcher = bind1(bind2,string.match)\n    > hex = matcher '^%x+$'\n\nPredicates are particularly useful for `ifind` and `ifilter`.  It's now easy to filter\nout strings from a array that match `blank` or `hex`, for instance.\n\nIt is not uncommon for Lua functions to return multiple useful values; sometimes the one\nyou want is the second value - this is what `take2` does:\n\n    > p = lfs.currentdir()\n    > = p\n    \"C:\\\\Users\\\\steve\\\\lua\\\\Microlight\"\n    > = splitpath(p)\n    \"C:\\\\Users\\\\steve\\\\lua\" \"Microlight\"\n    > basename = take2(splitpath)\n    > = basename(p)\n    \"Microlight\"\n    > extension = take2(splitext)\n    > = extension 'bonzo.dog'\n    \".dog\"\n\nThere is a pair of functions `map2fun` and `fun2map` which convert indexable objects into\ncallables and vice versa. Say I have a table of key/value pairs, but an API requires a\nfunction - use `map2fun`. Alternatively, the API might want a lookup table and you only\nhave a lookup function.  Say we have an array of objects with a name field. The `find`\nmethod will give us an object with a particular name:\n\n    > obj = objects:find ('X.name=Y','Alfred')\n    {name='Afred',age=23}\n    > by_name = function(name) return objects:find('X.name=Y',name) end\n    > lookup = fun2map(by_name)\n    > = lookup.Alfred\n    {name='Alfred',age=23}\n\nNow if you felt particularly clever and/or sadistic, that anonymous function could be\nwritten like so: (note the different quotes needed to get a nested string lambda):\n\n    by_name = bind1('X:find(\"X.name==Y\",Y)',objects)\n\n## Classes\n\nLua and Javascript have two important things in common; objects are associative arrays,\nwith sugar so that `t.key == t['key']`; there is no built-in class mechanism. This causes\na lot of (iniital) unhappiness. It's straightforward to build a class system, and so it\nis reinvented numerous times in incompatible ways.\n\n`class` works as expected:\n\n    Animal = ml.class()\n    Animal.sound = '?'\n\n    function Animal:_init(name)\n        self.name = name\n    end\n\n    function Animal:speak()\n        return self._class.sound..' I am '..self.name\n    end\n\n    Cat = class(Animal)\n    Cat.sound = 'meow'\n\n    felix = Cat('felix')\n\n    assert(felix:speak() == 'meow I am felix')\n    assert(felix._base == Animal)\n    assert(Cat.classof(felix))\n    assert(Animal.classof(felix))\n\n\nIt creates a table (what else?) which will contain the methods; if there's a base class,\nthen that will be copied into the table. This table becomes the metatable of each new\ninstance of that class, with `__index` pointing to the metatable itself. If `obj.key` is\nnot found, then Lua will attempt to look it up in the class. In this way, each object\ndoes not have to carry references to all of its methods, which gets inefficient.\n\nThe class is callable, and when called it returns a new object; if there is an `_init`\nmethod that will be called to do any custom setup; if not then the base class constructor\nwill be called.\n\nAll classes have a `_class` field pointing to itself (which is how `Animal.speak` gets\nits polymorphic behaviour) and a `classof` function.\n\n## Array Class\n\nSince Lua 5.1, the string functions can be called as methods, e.g. `s:sub(1,2)`. People\ncommonly would like this convenience for tables as well. But Lua tables are building\nblocks; to build abstract data types you need to specialize your tables. So `ml` provides\na `Array` class:\n\n    local Array = ml.class()\n\n    -- A constructor can return a _specific_ object\n    function Array:_init(t)\n        if not t then return nil end  -- no table, make a new one\n        if getmetatable(t)==Array then  -- was already a Array: copy constructor!\n            t = ml.sub(t,1)\n        end\n        return t\n    end\n\n    function Array:map(f,...) return Array(ml.imap(f,self,...)) end\n\nNote that if a constructor _does_ return a value, then it becomes the new object. This\nflexibility is useful if you want to wrap _existing_ objects.\n\nWe can't just add `imap`, because the function signature is wrong; the first argument is\nthe function and it returns a plain jane array.\n\nBut we can add methods to the class directly if the functions have the right first\nargument, and don't return anything:\n\n    ml.import(Array,{\n        -- straight from the table library\n        concat=table.concat,sort=table.sort,insert=table.insert,\n        remove=table.remove,append=table.insert,\n    ...\n    })\n\n`ifilter` and `sub` are almost right, but they need to be wrapped so that they return\nArrays as expected.\n\n    > words = Array{'frodo','bilbo','sam'}\n    > = words:sub(2)\n    {\"bilbo\",\"sam\"}\n    > words:sort()\n    > = words\n    {\"bilbo\",\"frodo\",\"sam\"}\n    > = words:concat ','\n    \"bilbo,frodo,sam\"\n    > = words:filter(string.match,'o$'):map(string.upper)\n    {\"BILBO\",\"FRODO\"}\n\nArrays are easier to use and involve less typing because the table functions are directly\navailable from them.  Methods may be _chained_, which (I think) reads better than the\nusual functional application order from right to left.  For instance, the sort utility\ndiscussed above simply becomes:\n\n    local Array = require 'ml'.Array\n    print(Array.collect(io.lines()):sort():concat '\\n')\n\nI don't generally recommend putting everything on one line, but it can be done if the\nurge is strong ;)\n\nThe ml table functions are available as methods:\n\n    > l = Array.range(10,50,10)\n    > = l:indexof(30)\n    3\n    > = l:indexby {1,3,5}\n    {10,30,50}\n    > = l:map(function(x) return x + 1 end)\n    {11,21,31,41,51}\n\nLua anonymous functions have a somewhat heavy syntax; three keywords needed to define a\nshort lambda.  It would be cool if the shorthand syntax `|x| x+1` used by Metalua would\nmake into mainstream Lua, but there seems to be widespread resistance to this little\nconvenience. In the meantime, there are _string lambdas_.  All ml functions taking\nfunction args go through `function_arg` which raises an error if the argument isn't\ncallable. But it will also understand 'X+1' as a shorthand for the above anonymous\nfunction. Such strings are expressions containing the placeholder variables `X`,`Y` and\n`Z` corresponding to the first, second and third arguments.\n\n    > A = Array\n    > a1 = A{1,2}\n    > a2 = A{10,20}\n    > = a1:map2('X+Y',a2)\n    {11,21}\n\nString lambdas are more limited. There's no easy (or efficient) way for them to access\nlocal variables like proper functions; they only see the global environment. BUt I\nconsider this a virtue, since they are intended to be 'pure' functions with no\nside-effects.\n\nArray is a useful class from which to derive more specialized classes, and it has\na very useful 'class method' to make adding new methods easy. In this case, we\nintend to keep strings in this subclass, so it should have appropriate methods for\n'bulk operations' using string methods.\n\n    Strings = class(Array)\n\n    Strings:mappers {  -- NB: note the colon: class method\n        upper = string.upper,\n        match = string.match,\n    }\n\n    local s = Strings{'one','two','three'}\n\n    assert(s:upper() == Strings{'ONE','TWO','THREE'})\n    assert(s:match '.-e$' == Strings{'one','three'})\n    assert(s:sub(1,2):upper() == Strings{'ONE','TWO'})\n\nIn fact, Array has been designed to be extended. Note that the inherited method `sub`\nis actually returning a Strings object, not a vanilla Array.\nThis property is usually known as _covariance_.\n\nIt's useful to remember that there is _nothing special_ about Array methods; they are\njust functions which take an array-like table as the first argument.  Saying\n`Array.map(t,f)` where `t` is some random array-like table or object is fine -\nbut the result _will_ be an Array.\n\n\n## Experiments!\n\nEvery library project has a few things which didn't make the final cut, and this is\nparticularly true of Microlight.  The `ml_properties` module allows you to define\nproperties in your classes. This comes from `examples/test.lua':\n\n    local props = require 'ml_properties'\n\n    local P = class()\n\n    -- will be called after setting _props\n    function P:update (k,v)\n        last_set = k\n    end\n\n    -- any explicit setters will be called on construction\n    function P:set_name (name)\n        self.myname = name\n    end\n\n    function P:get_name ()\n        last_get = 'name'\n        return self.myname\n    end\n\n    -- have to call this after any setters or getters are defined...\n    props(P,{\n        __update = P.update;\n        enabled = true,  -- these are default values\n        visible = false,\n        name = 'foo', -- has both a setter and a getter\n    })\n\n    local p = P()\n\n    -- initial state\n    asserteq (p,{myname=\"foo\",_enabled=true,_visible=false})\n\n    p.visible = true\n\n    -- P.update fired!\n    asserteq(last_set,'visible')\n\n`ml_range` (constributed by Dirk Laurie for this release) returns a function which works\nlike `ml.range`, except that it returns a Vector class which has element-wise addition\nand multiplication operators.\n\n`ml_module` is a Lua 5.2 module constructor which shows off that interesting function\n`ml.import`.  Here is the example in the distribution:\n\n    -- mod52.lua\n    local _ENV = require 'ml_module' (nil, -- no wholesale access to _G\n        'print','assert','os', -- quoted global values brought in\n        'lfs', -- not global, so use require()!\n        table -- not quoted, import the whole table into the environment!\n        )\n\n    function format (s)\n        local out = {'Hello',s,'at',os.date('%c'),'here is',lfs.currentdir()}\n        -- remember table.* has been brought in..\n        return concat(out,' ')\n    end\n\n    function message(s)\n        print(format(s))\n    end\n\n    -- no, we didn't bring anything else in\n    assert(setmetatable == nil)\n\n    -- NB return the _module_, not the _environment_!\n    return _M\n\nThis uses a 'shadow table' trick; the environment `_ENV` contains all the imports, plus\nthe exported functions; the actual module `_M` only contains the exported functions.  So\nit's equivalent to the old-fashioned `module('mod',package.seeall)` technique, except\nthat there is no way of accessing the environment of the module without using the debug\nmodule - which you would never allow into a sandboxed environment anyway.\n\n\n\n"
  },
  {
    "path": "test",
    "content": "lua examples/test.lua\n"
  },
  {
    "path": "test-mod52.lua",
    "content": "local m = require 'mod52'\n\nm.message 'you'\n\n-- the module itself only contains the exported functions\n-- (sandbox safe)\nfor k,v in pairs(m) do print(k,v) end\n"
  },
  {
    "path": "test.bat",
    "content": "lua examples\\test.lua\r\n"
  }
]