[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: (not) handling new programming idioms with grace
- From: Daurnimator <quae@...>
- Date: Mon, 16 Jul 2018 11:17:00 +1000
On 16 July 2018 at 03:49, Pierre Chapuis <catwell@archlinux.us> wrote:
> 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
>
What doesn't nicely translate to lua is what to do in the `yield` case:
local function foo()
with bar do
coroutine.yield(baz) -- maybe baz contains something based on `bar`
end
end
local f = coroutine.wrap(foo)
f()
if xyz then -- only *maybe* does the coroutine get resumed
f()
end