util.array an array library

util.array extends normal Lua tables with sevral convenient methods. In many cases, simply using a normal Lua table and the table library works just as well.

Creating

require "util.array" returns a constructor, simply pass a table to this function to create an array.

local array = require "util.array";
 
local myarray = array{ "my", "items", "here" };

Arrays can also be created by collecting the return values of an iterator:

local myarray = array.collect(io.lines("/etc/dictionary/words"));

Functions

These methods can be called two ways:

Create new array for result

array.method(existing_array, [params [, ...]])

Transform existing array into result

existing_array:method([params, ...])

map

Applies a function to all items.

local myarray = array { 1, 2, 3, 4 };
local function double(x)
    return x*2;
end
myarray:map(double);
-- myarray is now { 2, 4, 6, 8 }

filter

Filter all items trough a function which decides if the item is added to the result array or not.

local function larger_than_7(x)
    return x > 7;
end
myarray:filter(larger_than_7);
-- only items larger than 7 left

sort

Sort the array. Takes an optional comparison function.

array:sort(function (a, b) return a < b; end);

pluck

Given array of tables or arrays, return an array consisting of a specific item from those arrays.

local x = { foo = "bar" };
local myarray = array{ x, x, x };
local foos = myarray:pluck("foo");
-- foos is { "bar", "bar", "bar" }

reverse

Flip the array on its head.

local myarray = array { 1, 2, 3 };
local backwards = array();
array.reverse(backwards, myarray);

Methods

Some of these mutates the array.

random

Returns a random item from the array. No mutation.

shuffle

Shuffles the array, ie. sorts it in a random order.

append

Appends an all items from one array to another.

array1 = array{ 1, 2, 3 }
array2 = array{ 4, 5, 6 }
array:1:append(array2)
-- array1 is now { 1, 2, 3, 4, 5, 6 }

push

Push an item onto the end of the array.

myarray:push("x");

pop

Remove an item from the array.

local item = myarray:pop(4);

concat

Turns all items into strings and concatenates them togeather separated by sep.

print(myarray:concat(", "));

length

Returns the number of items in the array

print("myarray has " .. myarray:length() .. " items")

Operators

add

Summing two arrays results in a new array that contains all items from both arrays.

array3 = array1 + array2