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
.method(existing_array, [params [, ...]]) array
Transform existing array into result
:method([params, ...]) existing_array
map
Applies a function to all items.
local myarray = array { 1, 2, 3, 4 };
local function double(x)
return x*2;
end
:map(double);
myarray-- 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
:filter(larger_than_7);
myarray-- only items larger than 7 left
sort
Sort the array. Takes an optional comparison function.
:sort(function (a, b) return a < b; end); array
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();
.reverse(backwards, myarray); array
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.
= array{ 1, 2, 3 }
array1 = array{ 4, 5, 6 }
array2 :1:append(array2)
array-- array1 is now { 1, 2, 3, 4, 5, 6 }
push
Push an item onto the end of the array.
:push("x"); myarray
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.
= array1 + array2 array3