lua-users home
lua-l archive

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


I wrote, in an answer to Volkan Civelek:
> Now, we can see where the problem is:
> the "for i=n,pos,-1 do" loop is never run because pos > n (the first getn
> returns 0). So we always end up to "t[pos] = value", ie. we overwrite the
> previous value.
> Perhaps it is on purpose?
> 
> A way to get the result you expect is to rewrite the tinsert function as
> follow:
> 
> 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
>   if pos <= n then
>     t.n = n+1;
>     for i=n,pos,-1 do
>       t[i+1] = t[i]
>     end
>   else
>     t.n = pos
>   end
>   t[pos] = value
> end
> 
> ie. if we are inserting a value at a position higher than the current
> "size", it becomes the new size. Works at least with your code, I didn't
tested it
> thoroughly....

Neither Roberto nor Luiz reacted to my post. So I ask again: is my
correction completely stupid, or just outside the definition of tinsert?
Do you think tinsert function should be improved along the line of my
suggestion, or just the documentation improved to handle Volkan's case?

Regards.

-- 
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--

Sent through GMX FreeMail - http://www.gmx.net