lua-users home
lua-l archive

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


Hello list,

Once in a while I find myself writing code that looks like this:

if <some container is empty> then
    empty_stuff
else
    for k,v in pairs(container) do for_stuff end
end

or

if <some numerical [a,b,step] range is empty> then
    range_empty_stuff
else
    for i in a,b,step do for_stuff end
end

On those occasions I find myself wishing I could write this instead, where the else clause is run whenever the for clause was not entered.

for <iteration_stuff> do
    for_stuff
else
    else_stuff
end

Note that the behavior I am wishing for is not what python is offering: python's else clause is run at the end of the loop whether it was empty or not, and is skipped only if the loop is interrupted by break.

My gripe is the following: Currently the condition has to be written twice, and if for some reason the looping condition changes, I have to maintain the if condition as well. Code duplication doubles the chance of introducing a bug. The same remark applies to while loops.

I am aware that the language does not "need" this new syntax to express what I want to achieve. To this I can reply: the language does not need for and while loops at all either, since it has if and goto :-).

Introducing this change would not break existing Lua code, but are there any obvious reasons that could make this feature difficult to implement (for example syntactic ambiguities)?


Regards,

Benoit.

--
Benoit.