Every table is a distinct object.
local x = {1,2} -- table x
local t = {1,2} -- table t
print(x==y) -- false, because it's checking if table x is table t. It isn't. Every table is it's own object
When you use table.find, you’re essentially iterating over the table, and checking if the value is equal to whatever you want to find
function find(t,value)
for i,v in t do
if v==value then
return i
end
end
end
But now you are using a table as a value, and like I said before tables aren’t equal even if they have the same content, because every table is a unique object. So we can just iterate over the table and check like this.
local function tablesEqual(t1, t2)
if #t1 ~= #t2 then
return false
end
for i = 1, #t1 do
if t1[i] ~= t2[i] then
return false
end
end
return true
end
local t = {1,2}
local x = {1,2}
print(tablesEqual(t, x)) -- Output: true
There’s a problem with this. It only checks for tables one time. So it only accommodates a depth of 1. To fix, make it recursive.
local function tablesEqual(t1, t2)
-- Check if both tables are the same reference
if t1 == t2 then
return true
end
-- Check if both t1 and t2 are tables
if type(t1) ~= "table" or type(t2) ~= "table" then
return false
end
-- Check the number of keys in both tables
local function tableLength(tbl)
local count = 0
for _ in pairs(tbl) do
count = count + 1
end
return count
end
if tableLength(t1) ~= tableLength(t2) then
return false
end
-- Compare each key and value
for key, value1 in pairs(t1) do
local value2 = t2[key]
-- Check if the key exists in both tables
if value2 == nil then
return false
end
-- Recursively check for equality of nested tables
if type(value1) == "table" and type(value2) == "table" then
if not tablesEqual(value1, value2) then
return false
end
elseif value1 ~= value2 then
return false
end
end
return true
end
-- Example usage
local t1 = {1, 2, {a = 3, b = {4, 5}}}
local t2 = {1, 2, {a = 3, b = {4, 5}}}
local t3 = {1, 2, {a = 3, b = {4, 6}}}
print(tablesEqual(t1, t2)) -- Output: true
print(tablesEqual(t1, t3)) -- Output: false