配列の要素をフィルタリングする関数
配列の要素をフィルタリングする関数を書いてみた。
- 要素の順序を保ちながら削除する。
- フィルタ関数が false を返すと、その要素を削除する。
- フィルタ関数は、各要素に対して昇順に呼び出される。
そんだけです。
------------------------------------------------------------------------------- -- Filters an array "t" with the specified function "f". -- The function is called for each of the array elements in preceding order and -- returns true if the element is to be left or false to be removed. ------------------------------------------------------------------------------- function filter_array(t, f) local n = #t local i = 1 -- writing pointer local j = 1 -- reading pointer -- Filter elements. while j <= n do local v = t[j] if f(v) then -- Leave the element. t[i] = v i = i + 1 j = j + 1 else -- Remove the element. j = j + 1 end end -- Remove tailing elements. for k = n, i, -1 do t[k] = nil end end