lua-users home
lua-l archive

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


On Fri, Jul 20, 2018 at 12:44 PM Hisham <h@hisham.hm> wrote:
>
> On 19 July 2018 at 21:22, Soni "They/Them" L. <fakedme@gmail.com> wrote:
> > Oh, I just realized having a "return" or "break" inside the block/for loop
> > would cause issues... Hmm... Oh well, at least I tried I guess :/
>
> Yes, that's why people call for an actual feature to support this. It
> is not syntactic sugar: implicit immediate release of resources cannot
> be implemented in Lua as is.
>
> Note *implicit immediate* together:
>

It is not difficult to implement in lua a couple of functions that let
you to write:

```
local sequence = 'start'

barrier(function() -- Protect code region
  local a = {}

  setfinalizer(a, function(x) -- Call on scope exit
    assert(a == x)
    sequence = sequence .. '; closing a'
  end)

  sequence = sequence .. '; using a'
  error('an error')
end)

assert(sequence == 'start; using a; closing a')
```

It ask you to protect the critical code with 'barrier' and to set the
function to call on exit with 'setfinalizer'. It seems to me enough
implicit and immediate.

Is there some issue I can not see with this semantic?

Here the first, quickest, rawest implementation I can guess to (that
handles nested 'barrier' too):

```
local current_finalizer_list = {}
local function barrier(func)
  local old_finalizer_list = current_finalizer_list
  current_finalizer_list = {}
  pcall(func)
  for i=1,#current_finalizer_list do
    pcall(current_finalizer_list[i])
  end
  current_finalizer_list = old_finalizer_list
end
local function setfinalizer(value, func)
  local result = {}
  current_finalizer_list[1+#current_finalizer_list] = function()
    pcall(func,value)
  end
  return result
end
```

Please note, I am not arguing against any new feature proposed in the last days.