aboutsummaryrefslogtreecommitdiffstats
path: root/util/array.lua
diff options
context:
space:
mode:
Diffstat (limited to 'util/array.lua')
-rw-r--r--util/array.lua27
1 files changed, 26 insertions, 1 deletions
diff --git a/util/array.lua b/util/array.lua
index 150b4355..0b60a4fd 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -19,7 +19,13 @@ local type = type;
local array = {};
local array_base = {};
local array_methods = {};
-local array_mt = { __index = array_methods, __tostring = function (self) return "{"..self:concat(", ").."}"; end };
+local array_mt = {
+ __index = array_methods;
+ __name = "array";
+ __tostring = function (self) return "{"..self:concat(", ").."}"; end;
+};
+
+function array_mt:__freeze() return self; end
local function new_array(self, t, _s, _var)
if type(t) == "function" then -- Assume iterator
@@ -46,6 +52,19 @@ function array_mt.__eq(a, b)
return true;
end
+function array_mt.__div(a1, func)
+ local a2 = new_array();
+ local o = 0;
+ for i = 1, #a1 do
+ local new_value = func(a1[i]);
+ if new_value ~= nil then
+ o = o + 1;
+ a2[o] = new_value;
+ end
+ end
+ return a2;
+end
+
setmetatable(array, { __call = new_array });
-- Read-only methods
@@ -53,6 +72,12 @@ function array_methods:random()
return self[math_random(1, #self)];
end
+-- Return a random value excluding the one at idx
+function array_methods:random_other(idx)
+ local max = #self;
+ return self[((math.random(1, max-1)+(idx-1))%max)+1];
+end
+
-- These methods can be called two ways:
-- array.method(existing_array, [params [, ...]]) -- Create new array for result
-- existing_array:method([params, ...]) -- Transform existing array into result