Jump to content

Module:Includes: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
create
 
remove array size test -- always treat as conventional array when fromIndex is used
Line 3: Line 3:
return function (array, searchElement, fromIndex)
return function (array, searchElement, fromIndex)
fromIndex = tonumber(fromIndex)
fromIndex = tonumber(fromIndex)
if (fromIndex and #array > 0) then
if (fromIndex) then
if (fromIndex < 0) then
if (fromIndex < 0) then
fromIndex = #array + fromIndex + 1
fromIndex = #array + fromIndex + 1

Revision as of 20:07, 13 August 2024

-- Equivalent to JavaScript array.includes(searchElement) or
-- array.includes(searchElement, fromIndex), except fromIndex is 1 indexed
return function (array, searchElement, fromIndex)
	fromIndex = tonumber(fromIndex)
	if (fromIndex) then
		if (fromIndex < 0) then
			fromIndex = #array + fromIndex + 1
		end
		if fromIndex < 1 then fromIndex = 1 end
		local iter, a = ipairs(array)
		for _, v in iter, a, (fromIndex - 1) do
			if v == searchElement then
				return true
			end
		end
	else
		for _, v in pairs(array) do
			if v == searchElement then
				return true
			end
		end
	end
	return false
end