From edd7c99382fe1bf686cbd750db62bcb47c6294b6 Mon Sep 17 00:00:00 2001 From: rxi Date: Sun, 11 Jan 2015 14:58:12 +0000 Subject: [PATCH] Added lume.ripairs() function, updated README and tests --- README.md | 11 +++++++++++ lume.lua | 14 ++++++++++++++ test/test_lume.lua | 12 ++++++++++++ 3 files changed, 37 insertions(+) diff --git a/README.md b/README.md index 281f476..0c4f65e 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,17 @@ lume.hotswap("lume") -- Reloads the lume module assert(lume.hotswap("inexistant_module")) -- Raises an error ``` +### lume.ripairs(t) +Performs the same function as `ipairs()` but iterates in reverse; this allows +the removal of items from the table during iteration without any items being +skipped. +```lua +-- Prints "3->c", "2->b" and "1->a" on separate lines +for i, v in lume.ripairs({ "a", "b", "c" }) do + print(i .. "->" .. v) +end +``` + ### lume.rgba(color) Takes the 32bit integer `color` argument and returns 4 numbers, one for each channel, with a range of 0 - 255. The returned values can be used as the diff --git a/lume.lua b/lume.lua index 5813492..54e8eec 100644 --- a/lume.lua +++ b/lume.lua @@ -578,6 +578,20 @@ function lume.hotswap(modname) end +local ripairs_iter = function(t, i) + i = i - 1 + local v = t[i] + if v then return i, v end +end + +function lume.ripairs(t) + if t == nil then + return noop + end + return ripairs_iter, t, (#t + 1) +end + + function lume.rgba(color) local a = math_floor((color / 16777216) % 256) local r = math_floor((color / 65536) % 256) diff --git a/test/test_lume.lua b/test/test_lume.lua index 805351e..735f908 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -486,6 +486,18 @@ tests["lume.hotswap"] = function() testeq( type(err), "string" ) end +-- lume.ripairs +tests["lume.ripairs"] = function() + local t = { "a", "b", "c" } + local r = {} + for i, v in lume.ripairs(t) do + table.insert(r, { i, v }) + end + testeq( r, { { 3, "c" }, { 2, "b" }, { 1, "a" } }) + for i, v in lume.ripairs(nil) do + end +end + -- lume.rgba tests["lume.rgba"] = function() local r, g, b, a = lume.rgba(0x12345678)