lua-users home
lua-l archive

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


Duncan:
Although I am not completely clear why ipairs({}), t, -1 works, but I will read the iterators chapter again.

Thanks,

On Mon, Jun 23, 2008 at 7:15 PM, Duncan Cross <duncan.cross@gmail.com> wrote:
On Mon, Jun 23, 2008 at 11:22 AM, Ong hean kuan <mysurface@gmail.com> wrote:
> By default list constructed from table will start with index 1. I can force
> it to start at any value, such as 0 like this:
>
> t = { [0]='a','b','c','d','e','f' }
>
> But when i try to loop and access the item one by one, it seems to act
> strange:

pairs() returns its results in arbitrary order (which will in practice
usually start with the same results as ipairs before moving onto the
other key/value pairs only because of how tables are internally
stored, with an array and hash part, but you shouldn't rely on this).

> Instead of make 0 as first index of for loop, it place it as the last item.
>
> My question is:
> Is there any ways to make index 0 appear as 1st?

You could create a new version of ipairs that takes a second parameter
for the index to start at:

-- code start
local ipairsaux = ipairs({})
function ipairs2(t,i)
   return ipairsaux, t, (i or 1) - 1
end

t = { [0]='a','b','c','d','e','f' }
for i,v in ipairs2(t,0) do
   print (i," = ", v)
end
-- code end



--
Hean Kuan Ong
http://linux.byexamples.com
http://cc.byexamples.com
http://wordpress.byexamples.com