[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: (not) handling new programming idioms with grace
- From: Pierre Chapuis <catwell@...>
- Date: Sun, 15 Jul 2018 19:49:43 +0200
> I don't quite understand the problem, and maybe my ignorance shows,
> but ...
>
> What does a 'with' structure achieve that
>
> repeat
> local whatever
> ...
> if exception then break end
> ...
> until false
>
> does not?
I don't really get how this is similar to "with". The goal of "with" (i.e Python Context Managers [1]) is to make sure that something is executed at the beginning of a code block and something else at the end. So it would be more something like this in Lua terms:
with foo do
-- stuff
end
... works a bit like...
do
foo:__enter()
-- stuff
foo:__exit()
end
... except `__exit` is called no matter what happens in "stuff", including all those cases:
-- foo:__exit() is called once
local function f(foo)
with foo do
return
end
end
-- foo:__exit() is called twice
for i = 1, 5 do
with foo do
if i == 2 then
break
end
end
end
-- foo:__exit() is called once
with foo do
error()
end
This is important when you write code that deals with a resource that has to be released immediately and not asynchronously so you cannot rely on `__gc`, e.g. a database transaction, a mutex, arguably some file descriptors...
[1] https://docs.python.org/2.5/whatsnew/pep-343.html