lua-users home
lua-l archive

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

sure, same thing

i'm just used to using foreach(i) and never use (i)pairs
but if iterating over the table can be avoided by using a metatable (not
sure if it's possible but i guess so), i would go for the metatable
solution, especially if "TableSize" were a function that is called often or
if the tables were quite large

-----Ursprüngliche Nachricht-----
[] Im Auftrag von Brian Weed
Gesendet: Mittwoch, 31. August 2005 23:32
An: Lua list
Betreff: Re: AW: Size of a non numerical indexed table

Won't this do what he wants?

function TableSize(t)
    local i=0
    for k in pairs(t) do i = i + 1 end
    return i


steffenj wrote:

>hmmm, quick and dirty solution:
>local count = 0
>table.foreach(table, function(i, v)
>	-- don't count numerical indices:
>	if type(i) == "string" then
>		count = count + 1
>	end
>but it's definetely better to use a metatable and count all the string
>indizes when values are assigned to table indizes
>i haven't used metatables so far but the basics are to check, on
>wether the index is a string and wether the value is nil (delete index) or
>not (new index) and based on that, update a counter in the table
>i hope someone else can give an example...
>-----Ursprüngliche Nachricht-----
>[] Im Auftrag von Jose Marin
>Gesendet: Mittwoch, 31. August 2005 22:06
>Betreff: Size of a non numerical indexed table
>Well, I think that the subject tells my question!
>If it's a numerical indexed table, I can use
>table.getn, but if the table is indexed by names, how
>to get it's size?
>Yahoo! Acesso Grátis - Internet rápida e grátis. 
>Instale o discador agora!