[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Break statement, again.
- From: David Jeske <jeske@...>
- Date: Wed, 1 Sep 1999 15:47:06 -0700
I'm not concerned with whether the solution involves adding a break
statement or not. However, I have to second Fred's complaint about
"while()" being the only available looping structure. This pattern
right here:
On Wed, Sep 01, 1999 at 06:08:37PM -0300, Fred Bertsch wrote:
> [ code before test ]
> while test do
> [ code after test ]
> [ code before test ]
> end
>
> Which is obviously confusing and hard to maintain.
is littered through my Lua code. I have very few hard and fast rules,
but one of them is that replication of code leads to
multiple-maintaniance and annoying bugs, so don't do it. Only having a
while() loop structure forces me to duplicated the "code before test"
in two places, which I do not like at all.
Consider the ultra-simple operation of walking a table. This code was
taken right out of the lua reference manual's "foreach()" function:
local i, v = next(t, nil)
while i do
local res = f(i, v)
if res then
return res
end
i, v = next(t, i)
end
I despise the repition of the "i,v = next(t,i)" code. It may seem
innocuous in this case, however, if there is enough code in the loop
such that they don't fit on the same page, or if the amount of work
done during that code was more complicated, the maintaniance of that
replicated code becomes a chore.
The "break" syntax could solve this problem, but I'm not as crazy for
it. I think it makes it too easy to accidentally create infinite
loops. The above would be written as:
local v
local i = nil
while 1 do
i,v = next(t, i)
if not i then
break
end
local res = f(i, v)
if res then
return res
end
end
------------------------
I'd much prefer a syntax for assignment within expressions:
local i = nil
local v
while i,v = next(t,i) do
local res = f(i, v)
if res then
return res
end
end
Some special syntax might be required for allowing
better use of multiple-return values. (i.e. for having
the assignment evaluate to the value of one of the later
arguments)
For example, if I wanted "i,v = next(t,i)" to evaluate
to "v" instead of "i", we might need one of these:
(i,v = next(t,i))[v] -- some method of accessing the
(i,v = next(t,i))[2] -- return list as a table
(i,v = next(t,i)):v
(i,v = next(t,i)),v -- like the C comma-operator, but
-- evaluating to the value of the
-- last expression instead of the first
--
David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske@chat.net