Module:Utils: Difference between revisions
ArrowHead294 (talk | contribs) mNo edit summary |
allow functions table_contains and index_of to use optional comparison functions |
||
| Line 15: | Line 15: | ||
-- Check if a table contains x | -- Check if a table contains x | ||
function p.table_contains(tbl, x) | -- Accepts an optional comparison function that accepts two tables, returning | ||
for i = 1, #tbl do | -- true if x and tbl[i] have the same value. | ||
if x == tbl[i] then | function p.table_contains(tbl, x, compare_func) | ||
if compare_func ~= nil then | |||
-- Use compare function | |||
for i = 1, #tbl do | |||
if compare_func(x, tbl[i]) then | |||
return true | |||
end | |||
end | |||
else | |||
-- No compare function | |||
for i = 1, #tbl do | |||
if x == tbl[i] then | |||
return true | |||
end | |||
end | end | ||
end | end | ||
| Line 25: | Line 37: | ||
-- 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) | ||
function p.index_of(array, value) | -- Accepts an optional comparison function that accepts two tables, returning | ||
for i, v in ipairs(array) do | -- true if v and value have the same value. | ||
if v == value then | function p.index_of(array, value, compare_func) | ||
if compare_func ~= nil then | |||
-- Use compare function | |||
for i, v in ipairs(array) do | |||
if compare_func(v, value) then | |||
return i | |||
end | |||
end | |||
else | |||
-- No compare function | |||
for i, v in ipairs(array) do | |||
if v == value then | |||
return i | |||
end | |||
end | end | ||
end | end | ||