lua-users home
lua-l archive

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


On 20-07-2018 13:44, Hisham 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:

You can have implicit release of resources with __gc, but that's not
immediate. (And not being immediate is a problem: I have had
real-world bugs caused by that; files provided by the standard io
library do close() on __gc, but if you rely on that in a loop, your
code works fine for years until you run a loop on a directory with
thousands of files, and then you get a "too many open files" failure.)


Could having a "kill" library function solve this "immediate" problem?
ie. kill(o)
- calls __gc if exists
- then deletes o without waiting collecting
- afteruse is user's problem/responsibility

local kill = function(o) -- does not help!
  print("kill:", o.name, o)
  o = nil
  collectgarbage()
end

local mt = {__gc = function(o)
  print("gc:", o.name, o)
  kill(o)
end, }

a0 = {name="a0"}; setmetatable(a0, mt); print(a0.name, a0)
local a1 = {name="a1"}; setmetatable(a1, mt); print(a1.name, a1)
do
  local a2 = {name="a2"}; setmetatable(a2, mt); print(a2.name, a2)
end
kill(a0)
print("no gc", a0.name, a0) -- gc was not called!
local a3 = {name="a3"}; setmetatable(a3, mt); print(a3.name, a3)
a0 = nil; collectgarbage() -- here gc is called!



You can have immediate release of resources by calling foo:close() by
hand in every possible exit of your function, but that's not implicit.
(And not being implicit is a problem: throw the first stone they who
never forgot to close()/free()/release() a resource is some of their
code paths — that's why languages have garbage collection for memory
management, after all — but memory is not the only kind of resource
managed in a program.)

-- Hisham