From a8ddc7831a77f4d74963e1461eca531bdf531fdc Mon Sep 17 00:00:00 2001 From: Starbeamrainbowlabs Date: Sat, 29 May 2021 23:20:11 +0100 Subject: [PATCH] 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 --- worldeditadditions/utils/tables.lua | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/worldeditadditions/utils/tables.lua b/worldeditadditions/utils/tables.lua index 98dcbef..38a747a 100644 --- a/worldeditadditions/utils/tables.lua +++ b/worldeditadditions/utils/tables.lua @@ -69,7 +69,7 @@ end --- 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. -- @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|nil The function to execute on every item in the table. -- @returns table A new table containing the return values of the function. function worldeditadditions.table_map(tbl, func) local result = {} @@ -79,6 +79,22 @@ function worldeditadditions.table_map(tbl, func) 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: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. -- @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.