diff options
author | Matthew Wild <mwild1@gmail.com> | 2011-12-07 05:14:58 +0000 |
---|---|---|
committer | Matthew Wild <mwild1@gmail.com> | 2011-12-07 05:14:58 +0000 |
commit | 6c51171c432a9068270a580edd1ddd4753fde62c (patch) | |
tree | 65d62f327ab3465a6acdc5529503ed558eca772d /util/array.lua | |
parent | 0572f1ef240e909b4e16feda8964e56cfb1aa982 (diff) | |
download | prosody-6c51171c432a9068270a580edd1ddd4753fde62c.tar.gz prosody-6c51171c432a9068270a580edd1ddd4753fde62c.zip |
util.array: Expand some of the more basic methods to act more sensibly than their names suggested
Diffstat (limited to 'util/array.lua')
-rw-r--r-- | util/array.lua | 36 |
1 files changed, 27 insertions, 9 deletions
diff --git a/util/array.lua b/util/array.lua index cf586214..cbb051d3 100644 --- a/util/array.lua +++ b/util/array.lua @@ -25,6 +25,15 @@ end setmetatable(array, { __call = new_array }); +-- Read-only methods +function array_methods:random() + return self[math.random(1,#self)]; +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 +-- function array_base.map(outa, ina, func) for k,v in ipairs(ina) do outa[k] = func(v); @@ -67,11 +76,7 @@ function array_base.pluck(outa, ina, key) return outa; end ---- These methods only mutate -function array_methods:random() - return self[math.random(1,#self)]; -end - +--- These methods only mutate the array function array_methods:shuffle(outa, ina) local len = #self; for i=1,#self do @@ -98,10 +103,23 @@ function array_methods:append(array) return self; end -array_methods.push = table.insert; -array_methods.pop = table.remove; -array_methods.concat = table.concat; -array_methods.length = function (t) return #t; end +function array_methods:push(x) + table.insert(self, x); +end + +function array_methods:pop(x) + local v = self[x]; + table.remove(self, x); + return v; +end + +function array_methods:concat(sep) + return table.concat(array.map(self, tostring), sep); +end + +function array_methods:length() + return #self; +end --- These methods always create a new array function array.collect(f, s, var) |