Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@vn971

This comment has been minimized.

Copy link

@vn971 vn971 commented Apr 7, 2018

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" }

@PhB-fr

This comment has been minimized.

Copy link

@PhB-fr 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