• Subject: RE: list iteration for statement
• From: "Philippe Lhoste" <PhiLho@...>
• Date: Thu, 26 Apr 2001 11:43:11 +0200

```John Belmonte wrote:
> I've been thinking it would be nice to have another form of the
> for loop on
> top of two we have now, for iterating lists:
>
>     for val in list do
>         print(val)
>     end
>
> The equivalent in the Lua as it is now:
>
>     for i = 1, getn(list) do
>         local val = list[i]
>         print(val)
>     end
>
> Such iteration (where the list is not modified) is very common.
> My argument
> for adding this new form is that it's more terse, less error prone
> (forgetting the local qualifier, etc), and faster if the list
> happens to be
> a global.
>
> Any thoughts?

have a mechanism for this.
Excerpt from the manual:

>>>
foreach (table, func)
Executes the given func over all elements of table. For each element, the
function is called with the index and respective value as arguments. If the
function returns any non-nil value, then the loop is broken, and this value
is returned as the final value of foreach. This function could be defined in
Lua:
function foreach (t, f)
for i, v in t do
local res = f(i, v)
if res then return res end
end
end

The behavior of foreach is undefined if you change the table t during the
traversal.

foreachi (table, func)
Executes the given func over the numerical indices of table. For each index,
the function is called with the index and respective value as arguments.
Indices are visited in sequential order, from 1 to n, where n is the result
of getn(table) (see Section 6.1). If the function returns any non-nil value,
then the loop is broken, and this value is returned as the final value of
foreachi. This function could be defined in Lua:
function foreachi (t, f)
for i=1,getn(t) do
local res = f(i, t[i])
if res then return res end
end
end
<<<

Regards.

--._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`·._.·´¯`--

```