Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created September 26, 2012 19:59
Show Gist options
  • Save FGRibreau/3790217 to your computer and use it in GitHub Desktop.
Save FGRibreau/3790217 to your computer and use it in GitHub Desktop.
Lua table.filter (JavaScript Array::filter equivalent)
-- table.filter({"a", "b", "c", "d"}, function(o, k, i) return o >= "c" end) --> {"c","d"}
--
-- @FGRibreau - Francois-Guillaume Ribreau
-- @Redsmin - A full-feature client for Redis http://redsmin.com
table.filter = function(t, filterIter)
local out = {}
for k, v in pairs(t) do
if filterIter(v, k, t) then out[k] = v end
end
return out
end
@PhB-fr
Copy link

PhB-fr commented Feb 11, 2019

Note/warning: If you try to iterate the result using ipairs, it'll break (not give you all keys).
The real result of the example (line 1) actually is: { [3] = "c", [4] = "d" }

To make the output a regular iterable array, you can replace :
out[k] = v
by
table.insert(out,v)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment