lua-users home
lua-l archive

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


David Manura writes:
> a "scoped guard" statement (from the D language)

Is rewriting this type of the thing the following way relatively clear?

function f(filename, filename2)
  local x = 1
  catch err do
    if not(err == 'foo') then error(err) end  -- re-raise
    print('handling', err, x)  -- note: x == 1 here
  end
  local x = 2
  local h = io.open (filename)
  finally if h then h:close() end end
  ...
  local h2 = io.open (filename2)
  finally if h2 then h2:close() end end
  ...
  if g() then error 'foo' end
  ...
  return h:read '*a', h2:read '*a'
end
print(f("data.txt", "data2.txt"))

as opposed to

function f(filename, filename2)
  local x = 1
  try
    local x = 2
    local h = io.open (filename)
    ...
    local h2 = io.open (filename2)
    ...
    if g() then error 'foo' end
    ...
    ...
  catch err do
    if not(err == 'foo') then error(err) end  -- re-raise
    print('handling', err, x)  -- note: x == 1 here
  finally
    -- note: this assumes h:close() doesn't raise;
    -- if it does, we might want to nest another try-block.
    if h then h:close() end
    if h2 then h2:close() end
  end
end
print(f("data.txt", "data2.txt"))