Module:Utils: Difference between revisions
allow functions table_contains and index_of to use optional comparison functions |
m minor renaming of args |
||
| Line 14: | Line 14: | ||
end | end | ||
-- Check if a table contains | -- Check if a table contains the given value | ||
-- Accepts an optional comparison function that accepts two tables, returning | -- Accepts an optional comparison function that accepts two tables, returning | ||
-- true if | -- true if value and tbl[i] have the same value. | ||
function p.table_contains(tbl, | function p.table_contains(tbl, value, compare_func) | ||
if compare_func ~= nil then | if compare_func ~= nil then | ||
-- Use compare function | -- Use compare function | ||
for i = 1, #tbl do | for i = 1, #tbl do | ||
if compare_func( | if compare_func(value, tbl[i]) then | ||
return true | return true | ||
end | end | ||
| Line 28: | Line 28: | ||
-- No compare function | -- No compare function | ||
for i = 1, #tbl do | for i = 1, #tbl do | ||
if | if value == tbl[i] then | ||
return true | return true | ||
end | end | ||
| Line 38: | Line 38: | ||
-- Return the first index with the given value (or nil if not found) | -- Return the first index with the given value (or nil if not found) | ||
-- Accepts an optional comparison function that accepts two tables, returning | -- Accepts an optional comparison function that accepts two tables, returning | ||
-- true if v | -- true if value and v have the same value. | ||
function p.index_of(array, value, compare_func) | function p.index_of(array, value, compare_func) | ||
if compare_func ~= nil then | if compare_func ~= nil then | ||