Software /
code /
prosody
Comparison
util/array.lua @ 9529:6a1e7723208b
util.array: Add __div for parity with util.set
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Sun, 21 Oct 2018 15:38:55 +0100 |
parent | 9528:1af7cc3b9747 |
child | 10592:9918b4b0cd58 |
comparison
equal
deleted
inserted
replaced
9528:1af7cc3b9747 | 9529:6a1e7723208b |
---|---|
50 return false; | 50 return false; |
51 end | 51 end |
52 return true; | 52 return true; |
53 end | 53 end |
54 | 54 |
55 function array_mt.__div(a1, func) | |
56 local a2 = new_array(); | |
57 local o = 0; | |
58 for i = 1, #a1 do | |
59 local new_value = func(a1[i]); | |
60 if new_value ~= nil then | |
61 o = o + 1; | |
62 a2[o] = new_value; | |
63 end | |
64 end | |
65 return a2; | |
66 end | |
67 | |
55 setmetatable(array, { __call = new_array }); | 68 setmetatable(array, { __call = new_array }); |
56 | 69 |
57 -- Read-only methods | 70 -- Read-only methods |
58 function array_methods:random() | 71 function array_methods:random() |
59 return self[math_random(1, #self)]; | 72 return self[math_random(1, #self)]; |
73 end | |
74 | |
75 -- Return a random value excluding the one at idx | |
76 function array_methods:random_other(idx) | |
77 local max = #self; | |
78 return self[((math.random(1, max-1)+(idx-1))%max)+1]; | |
60 end | 79 end |
61 | 80 |
62 -- These methods can be called two ways: | 81 -- These methods can be called two ways: |
63 -- array.method(existing_array, [params [, ...]]) -- Create new array for result | 82 -- array.method(existing_array, [params [, ...]]) -- Create new array for result |
64 -- existing_array:method([params, ...]) -- Transform existing array into result | 83 -- existing_array:method([params, ...]) -- Transform existing array into result |