From 1cedfd94642a80ee4486b0c5e43e105f3dc77586 Mon Sep 17 00:00:00 2001 From: rxi Date: Mon, 3 Mar 2014 12:08:11 +0000 Subject: [PATCH] Added lume.each() function --- README.md | 10 +++++++++- lume.lua | 11 ++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d0c4566..de5d175 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,15 @@ Iterates the supplied iterator and returns an array filled with the values. lume.array(pairs({a = 1, b = 2})) -- Returns {"a", "b"} ``` +### lume.each(t, fn, ...) +Iterates the table `t` and calls the function `fn` on each value followed by +the supplied additional arguments; if `fn` is a string the method of that name +is called for each value. The function returns `t` unmodified. +```lua +lume.each({1, 2, 3}, print) -- Prints "1", "2", "3" on separate lines +lume.each({a, b, c}, "move", 10, 20) -- Does x:move(10, 20) on each value +``` + ### lume.map(t, fn) Applies the function `fn` to each value in table `t` and returns a new table with the resulting values. @@ -132,7 +141,6 @@ exist in the table. lume.find({"a", "b", "c"}, "b") -- Returns 2 ``` - ### lume.slice(t [, i [, j]]) Mimics the behaviour of Lua's `string.sub`, but operates on an array rather than a string. Creates and returns a new array of the given slice. diff --git a/lume.lua b/lume.lua index 9a20ce4..2bb5dd8 100644 --- a/lume.lua +++ b/lume.lua @@ -80,6 +80,16 @@ function lume.array(...) end +function lume.each(t, fn, ...) + if type(fn) == "string" then + for _, v in pairs(t) do v[fn](v, ...) end + else + for _, v in pairs(t) do fn(v, ...) end + end + return t +end + + function lume.map(t, fn) local rtn = {} for k, v in pairs(t) do rtn[k] = fn(v) end @@ -145,7 +155,6 @@ function lume.find(t, value) end - function lume.slice(t, i, j) i = i or 1 j = j and (j < 0 and (#t + j) or j) or (#t - i + 1)