lua-users home
lua-l archive

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


David Given wrote:
> The whole goto-considered-harmful myth has done the world a vast disservice.
> goto is *entirely* the right construct for dealing with certain software
> problems: for example, state machines.

I thought coroutines were entirely the right construct for state machines.

> (And, in fact, Dijkstra was completely
> up front about this in his original paper.) They're also very handy for doing
> things like cleanup on error:
> 
> 	if not function1() then
> 		goto exit
> 	end
> 	if not function2() then
> 		goto cleanup1_and_exit
> 	end
> 	if not function3() then
> 		goto cleanup2_and_exit
> 	end
> 	return success
> 
> 	cleanup3()
> cleanup2_and_exit:
> 	cleanup2()
> cleanup1_and_exit:
> 	cleanup1()
> 	return failure
> 
> The alternative approach is to use lots of nested if statements, which can
> quickly get out of control if your logic is at all complicated --- and if you
> need an exit strategy from within, say, a loop, you're basically stuffed. You
> have to either duplicate code or use flag variables.

Actually, neither goto or nested if's are readable, but fortunately
these two are not the only solutions as you suggest.  Scope guards are
easy to implement in Lua, although it requires function closures from
which you cannot exit the surrounding function.  That problem could be
addressed with a construct along Python's "with" statement.  Now that
would change what could be done in Lua.

> ...and while I'm whinging, it would also be nice to have some
> try/catch/finally/throw syntactic sugar around pcall and error. I know it's
> Not The Lua Way to provide high-level functionality like that, but exceptions
> are so useful, and doing them yourself with pcall is so wordy, that I reckon
> it's worth doing in this case.

Yes, minus "finally".   try-finally as a solution for exception safety
or resource cleanup is dead and best eschewed by modern languages.
(http://www.digitalmars.com/d/exception-safe.html)