Lulu Arrays — Mapping & Transforming
Introduction
If you have imported the lulu.Array class as
local Array = require 'lulu.Array'Then, you have access to the following methods:
Array:map(fun,...)
Returns a new Array, which results from applying fun to each value in self.
Array:transform(fun,...)
Transform an Array in place by applying fun to each top-level value. This method returns the transformed self and is ready for further processing.
Array:map
Classic “functional” method that creates a new table by applying fun to each value in self.
In this implementation, the function also passes any extra ... arguments in the call to Array:map(fun,...).
If the returned Array is the result, then for each index k, we set:
result[k] = fun(self[k],...)Of course, fun may ignore those extra arguments entirely, and Lua is happy to call a function with multiple arguments, even if it only uses the first one.
Example:
local lower = Array{'warning', 'notice', 'hint'}
local upper = lower:map(string.upper)
1putln("lower: %t", lower)
putln("upper: %t", upper)- 1
-
The examples on this page use
putlnfromlulu.scribefor formatted printing.
Output:
lower: ["warning", "notice", "hint"]
1upper: ["WARNING", "NOTICE", "HINT"]- 1
-
We mapped the Lua standard
string.upper(...)method over every value in thelowerarray.
Array:transform
This method is like map above except that it works in place, so for each index k, we set:
self[k] = fun(self[k],...)Example:
local admonitions = Array{'warning', 'notice', 'hint'}
putln("admonitions: %t", admonitions)
admonitions:transform(string.upper)
putln("admonitions: %t", admonitions)Output:
admonitions: ["warning", "notice", "hint"]
admonitions: ["WARNING", "NOTICE", "HINT"]