Jump to content

Module talk:TableTools

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Verdy p (talk | contribs) at 07:50, 2 February 2014 (Created page with '== removeDuplicate does not remove duplicate NaN == <source lang="lua"> function p.removeDuplicates(t) checkType('removeDuplicates', 1, t, 'table') local isNan...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

removeDuplicate does not remove duplicate NaN

function p.removeDuplicates(t)
	checkType('removeDuplicates', 1, t, 'table')
	local isNan = p.isNan
	local ret, exists = {}, {}
	for i, v in ipairs(t) do
		if isNan(v) then
			-- NaNs can't be table keys, and they are also unique, so we don't need to check existence.
			ret[#ret + 1] = v
		else
			if not exists[v] then
				ret[#ret + 1] = v
				exists[v] = true
			end
		end	
	end
	return ret
end

This should be:

function p.removeDuplicates(t)
	checkType('removeDuplicates', 1, t, 'table')
	local isNan = p.isNan
	local ret, exists, hasNan = {}, {}, nil
	for i, v in ipairs(t) do
		if isNan(v) then
			-- NaNs can't be table keys in exists[], and they are also equal to each other in Lua.
			-- But we want only one Nan in ret[], and there may be multiple Nan's in t[].
			if not hasNan then
				ret[#ret + 1] = v
				hasNan = true
			end
		else
			if not exists[v] then
				ret[#ret + 1] = v
				exists[v] = true
			end
		end	
	end
	return ret
end

-- verdy_p (talk) 07:50, 2 February 2014 (UTC)[reply]