wea.table_filter: add API function

Really, Lua should have this already. At this rate, I'll be implementing 
the entire Javascript standard library... :P
This commit is contained in:
Starbeamrainbowlabs 2021-05-29 23:20:11 +01:00
parent b23f353b19
commit a8ddc7831a
Signed by: sbrl
GPG key ID: 1BE5172E637709C2

View file

@ -69,7 +69,7 @@ end
--- Executes the given function on every item in the given table. --- Executes the given function on every item in the given table.
-- Ignores return values that are nil and doesn't insert them into the table. -- Ignores return values that are nil and doesn't insert them into the table.
-- @param tbl table The table to operate on. -- @param tbl table The table to operate on.
-- @param func function The function to execute on every item in the table. -- @param func function<any>:any|nil The function to execute on every item in the table.
-- @returns table A new table containing the return values of the function. -- @returns table A new table containing the return values of the function.
function worldeditadditions.table_map(tbl, func) function worldeditadditions.table_map(tbl, func)
local result = {} local result = {}
@ -79,6 +79,22 @@ function worldeditadditions.table_map(tbl, func)
end end
end end
--- Filters the items in the given table using the given function.
-- The function is executed for each item in the list. If it returns true, the
-- item is kept. If it returns false, the item is discarded.
-- @param tbl table The table of values to filter.
-- @param func function<any>:bool The filter function to execute - should return a boolean value indicating whether the item provided as the first argument should be kept
-- @returns table A new table containing the values that the given function returned true for.
function worldeditadditions.table_filter(tbl, func)
local result = {}
for i,value in ipairs(tbl) do
if func(value) then
table.insert(result, value)
end
end
return result
end
--- Builds a new table with the elements of the given table appearing at most once. --- Builds a new table with the elements of the given table appearing at most once.
-- @param tbl table The table of values to make unique. -- @param tbl table The table of values to make unique.
-- @returns table A new table containing the values of the given table appearing at most once. -- @returns table A new table containing the values of the given table appearing at most once.