lua-users home
lua-l archive

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


On Mon, Oct 13, 2008 at 5:01 PM, Jon Nalley <lists@bluebot.org> wrote:
> I am having some difficulty understanding what is going on in the code below
> and was hoping someone could enlighten me.
>
>
> t = { 'one', nil, 'three' }
>
> print(#t) -- 3
> print(table.maxn(t)) -- 3
>
> table.insert(t, 5, 'four')
>
> print(#t) -- 1
> print(table.maxn(t)) -- 5
>
>
> Why does #t change to 1 after the table.insert()?
>
> If I specify a position < 5 to table.insert() then #t is not set to 1 and is
> the same as table.maxn(t).

#t isn't guaranteed to point to the largest index, it returns any integer where:

t[#t] ~= nil and t[#t+1] == nil

in your initial table { 'one', nil, 'three' }, it could return 1 or 3.
 after you insert 'four' at index 5, it could return 1, 3, or 5.

in short: don't use #t if your table have 'holes'

-- 
Javier