[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: for and table.n
- From: Nick Trout <Nick.Trout@...>
- Date: Mon, 11 Feb 2002 17:46:43 -0000
Could the table.n problem be discussed and resolved at the Harvard meeting
please? I believe this is an issue to do with the standard libraries.
list = { "a","b","c" }
tinsert(list,"d")
-- 1.
for _,v in list do print(v) end
-- 2.
foreach(list, function(i,v) print(v) end)
-- 3.
for i = 1,getn(list) do
local v=list[i]
print(v)
end
-- 4.
foreachi(list, function(i,v) print(v) end)
When printing the list, the first 2 solutions include n. The latter, more
bulky 2, do not. I would like Lua to not add n to a table out of the box. I
found the for statement a very useful addition to Lua. It is a real pain
having use the later 2 solutions when I want to iterate over a list, or I
have to override tinsert(),tremove() and getn().
The best solution I have encountered so far is using weak keyed tables to
hold n for each table and the addition of setn(). I would like to see a
solution like :-
_tn = {}
function getn (t)
-- if type(t.n) == "number" then return t.n end
if _tn[t] then return _tn[t] end
local max = 0
for i, _ in t do
if type(i) == "number" and i>max then max=i end
end
return max
end
function setn(t,n) _tn[t] = n end
function tinsert (t, ...)
local pos, value
local n = getn(t)
if arg.n == 1 then
pos, value = n+1, arg[1]
else
pos, value = arg[1], arg[2]
end
-- t.n = n+1;
setn(t,n+1)
for i=n,pos,-1 do
t[i+1] = t[i]
end
t[pos] = value
end
function tremove (t, pos)
local n = getn(t)
if n<=0 then return end
pos = pos or n
local value = t[pos]
for i=pos,n-1 do
t[i] = t[i+1]
end
t[n] = nil
-- t.n = n-1
setn(t,n-1)
return value
end
Its not just a pain because the iteration problem, but also because it can
cause conflicts...
http://lua-users.org/wiki/LuaTableSize
Regards,
Nick