Lua provides only a few methods to work with tables. This package is an attempt to extend Lua's capabilities to work with array-like structures by introducing a wrapper with a bunch of useful and common methods which other programming languages have.
Via LuaRocks:
luarocks install luarray
Or directly download and include init.lua file
The module exports only one constructor function. If you ever worked with PHP then the usage will be very familiar:
local array = require "luarray" -- Require the module
local a = array("a", "b", "c") -- Instantiate an array, like in PHP
a:map(function (i, elt) return elt:upper() end):reverse():join() -- "CBA"
- Negative indexing
- Object-oriented approach
nil
as an element- Stack methods
- Overloaded operators
- Consistency
Methods that accept indexes can also accept negative ones. In such case the counting starts from the end of an array:
array("a", "b", "c"):slice(-2) -- array("b", "c")
It also applies to the index operator:
array("a", "b", "c")[-1] -- "c"
Each call to array()
function creates a table with methods that can be chained:
array("a", "b", "c"):reverse():join() -- "cba"
Ordinary lua tables consider nils as a gap, which means that the behaviour of length operator or loops could be confusing at first glance. The constructor and methods consider nil
as a regular element:
local a = array("a", nil, "c", nil)
a:len() -- 4
An array could also be used as a stack - the library provides such methods:
local a = array()
a:addend("a")
a:addend("b")
a:delend()
print(a) -- array("a")
The library overloads the next metamethods for arrays:
__index()
for indexing__newindex()
for direct assigning__len()
for retrieving length__concat()
for concatenating arrays__pairs()
for usage inpairs()
function__eq()
for deep comparison between arrays__mul()
for intersecting__add()
for union__sub()
for subtraction
Example:
local a = array("a")
a = a..array("b") -- array("a", "b")
a[2] -- "b"
a[3] = "c"
print(a == array("a", "b", "c"))
> true
a = a - array("b") -- array("a", "c")
Methods that accept closures will pass index and value to them in that order only - the same way as pairs()
and other functions return key in first place and then the value:
array():map(function (i, elt) --[[ ... ]] end)
Also, methods that operate with array ends are named appropriately: reduceend
, addend
, delstart
, addstart
and so on.
To get all available API, please refer to api.md or run node api.js
to generate documentation.
NOTE: Methods that return an array create a new one instead of modifying the current array (for a few exceptions) - the same way as JavaScript or PHP do.
Install luaunit:
luarocks install luaunit
Then run lua test.lua
on Windows or ./lua test.lua
on Linux