lua-users home
lua-l archive

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


I think the length of lua table is a big trick.:)

function table.len(t)
local len=0
table.foreach(t,
function (k,v)
len=len+1
end
)
return len;
end

print(table.len({1,2,nil,4}))
print(table.len({nil,1,2,nil,3,nil,4}))
print(table.len({nil,'a',2,nil,3,nil,4,nil,'b'}))
print(table.len({2,3,4,5,6}))
t={}
t.a=nil
t.b=1
t.c=2
t.d=nil
t.e=3
t[3]='a'
print(table.len(t))
function table.compare(t1,t2)
if table.len(t1)~=table.len(t2) then return false; end
table.foreach(t1,
function(k,v)
if v~=t2[k] and type(v)~='table' then
return false;
elseif v~=t2[k] then
return table.compare(v,t2[k])
end
end
)
return true;
end
tt={a=1,nil,2,{}}
tt1={1,2,t,3,b=3,d=nil}
tt2={1,nil,b=3,2,nil,c=nil,3,t}
print(table.compare(tt1,tt2))

On Tue, Dec 30, 2008 at 11:48, Alex Davies <alex.mania@iinet.net.au> wrote:
G.H. wrote:
Unless t1 = {1,2,3} and t2 = {['a'] = 1, ['b']...} or t2 = {1,2,3, ...}
Such as they'll be rejected immediatly. But it isn't so useful anyway  :)

It's worth remembering that Lua (and the current implementation) doesn't actually guarantee two identical holey tables will have the same length.
So comparing lengths isn't a good shortcut unfortunately..

As an example running this on Lua 5.1:

local t1 = {1, 2, nil, 4, nil}
local t2 = {1, 2}
t2[4] = 4
print(#t1..", "..#t2)

will print: 2, 4

- Alex



--
Regards,
Linker Lin
linker.m.lin@gmail.com