[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: An alternative to the "continue" statement
- From: Fabien <fleutot+lua@...>
- Date: Tue, 26 Feb 2008 15:00:18 +0100
Since the regular rant about the missing "continue" statement resurfaced again, I thought I might point to an experiment I did, which covers most of the cases where I'd otherwise miss "continue":
Basically, it lets qualify a loop header with additional properties like "if", "while", "until", "for". Many "break"s in for loops can be replaced with:
for k, v in pairs(some_table) until leaving_condition do
for i=1, 10 while not_leaving do
and most "continue" statements can be replaced with:
for k, v in pairs(some_table) if not some_reason_to_skip do
I like this (still quite experimental) syntax because it integrates the skipping/breaking condition in the loop header, and this is where it belongs: the purpose of the "for loops" syntax, in most languages, is that it describes how the control flow will unfold in a single, well-identified line. When one simulates such loops with a "while...do", the condition, stopping and iteration bits are dispatched in various places, thus making code reading significantly more tedious.
"break" and "continue" statements deeply alter this control flow, possibly from deep within the loop body; this ought to be stated in the loop header line whenever possible.
NB: I'm fully aware that there are use cases for "continue" which aren't addressed by this extension, but:
- that wasn't the subject of the experiment,
- adding a "continue" statement is pretty trivial, and already done by some tiny sample, somewhere in the distro
- until now, this extension happened to cover all the real-life cases where I'd use continue.