lua-users home
lua-l archive

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


On Sun, 2019-06-23 at 13:59 +0200, Dirk Laurie wrote:
> Is there any good, sound reason why a local variable needs to remain
> in limbo after it has gone out of scope?
> 
> If not, we don't need <toclose> at all.

Thing is, variable != value. <toclose> is about closing variable when
it leaves scope, not to make garbage collector removing variable when
it have no more refs immediately.

I look at this as an attempt to add RAII support to Lua without
seriously breaking exsisting code. For example:

function processFile(fname)
  local <toclose> f = assert(io.open(fname, 'r'))
  ... perform operations ...
  return textProcessed
end

When function exit (by any means, eiter return or error), file will be
closed without need to do so manually or waiting for GC.

However, this example is different:

function extractFile(archive, archpath)
  local <toclose> archfile = assert(io.open(archive, 'r'))
  ... extract file ...
  local file = assert(io.open(tmppath, 'r'))
  ... some checks/cleanup ...
  return file
end

Here we want to return file and don't want to close it when we exit the
function by returning it, so <toclose> doesn't fit our needs. (Strictly
speaking, that still would be great to close it if checks caused an
error, but this introduce some overhead):

...
  local <toclose> file = assert(io.open(tmppath, 'r'))
  ... some checks/cleanup ...
  local retfile = file
  file = nil
  return retfile
end

If you're familiar with C/C++, you probably may think about <toclose>
variables as a stack ones. If you return it by value, you'll be fine.
But if you return it as reference, you'll get invalid results (less
dramatic than in C/C++, but still).

One limitation here is that in Lua define what is passed by reference
(functions, tables, userdatas) and what does not (everything else).