lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Here's something I think might work for the requested case. It makes use
of next to count the items in the table b while it's iterating table a
using pairs (matching order does not matter).

function	compareTables(a, b)
	local	bi = nil;

	for k,v in pairs(a) do
		bi = next(b, bi);
		if v ~= b[k] then
			return false;
		end

		if bi == nil then
			return false;
		end
	end

	if next(b, bi) ~= nil then
		return false;
	end

	return true;
end

a = { x = 1, y = 2, z = 3 };
b = { x = 1, y = 2, z = 3 };
c = { x = 1, y = 3, z = 2 };
d = { x = 1, y = 2, z = 3, w = 4 };
e = { x = 1, z = 3, y = 2 };

print(compareTables(a,b), compareTables(a, c), compareTables(a, d),
compareTables(d, a), compareTables(a, e), compareTables({}, {}));