[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: The new (5.0) for syntax
- From: Peter Shook <pshook@...>
- Date: Thu, 13 Jun 2002 20:20:21 -0400
On Thursday 13 June 2002 07:18, Philippe wrote:
> t = { "a", "b", "c" }
> for i, k in nexti(t) do print(i, k) end
> for k, v in next, t do print(k, v) end
> for k, v in t do print(k, v) end
> The results are identical.
In older versions of Lua, the 'next' function may return the elements of 't'
out of order. Has this changed?
For those who are new to Lua, the last two statements are different in that
all the fields of 't' are traversed (even the key/value pairs), whereas
'nexti' traverses the numerical indices of 't' from 1 up to the first 'nil'
element. In the example above, 't' has no key/value pairs and no 'nil'
elements so it doesn't matter, but the example below shows the difference:
$ lua
Lua 5.0 (work0) Copyright (C) 1994-2002 Tecgraf, PUC-Rio
>
> t = { 10,20,nil,30, a='one',b='two' }
> for i = 1,table.getn(t) do print(i,t[i]) end
1 10
2 20
3 nil
4 30
> for i,v in nexti(t) do print(i,v) end
1 10
2 20
> for i,v in nexti,t do print(i,v) end
1 10
2 20
> for n,v in t do print(n,v) end
1 10
2 20
4 30
a one
b two
> for n,v in next,t do print(n,v) end
1 10
2 20
4 30
a one
b two
>
- Peter