Module:Utils: Difference between revisions

Ganaram inukshuk (talk | contribs)
allow functions table_contains and index_of to use optional comparison functions
Ganaram inukshuk (talk | contribs)
m minor renaming of args
Line 14: Line 14:
end
end


-- Check if a table contains x
-- 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 x and tbl[i] have the same value.
-- true if value and tbl[i] have the same value.
function p.table_contains(tbl, x, compare_func)
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(x, tbl[i]) then
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 x == tbl[i] then
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 and value have the same value.
-- 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