lua-users home
lua-l archive

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


To be close variable ( https://www.lua.org/manual/5.4/manual.html#3.3.8 ) in form it implemented is harmful by nature.

They introduces unnecessary complexity. This implementation creates more problems than they solve.  It will lead to bugs on all levels. Even more this problems will be hard to find and debug.

Let me show small example:

#!lua54
-- https://gist.githubusercontent.com/kov-serg/360d9b7e4a3bb4c67585dfb1068adf6c/raw/cab4ca0d794a31d780d50f6c57138cd5643b569c/lua54_tbv.lua

print(_VERSION)

function test(name)
    return setmetatable({},{
        __close=function() print("__close "..name) end,
        __gc=function() print("__gc "..name) end,
    })
end

do -- 1. programmer should know what is variable is to-be-closed or not
   -- This is introduction of unnecessary complexity
   local v1 = test "v1"
   local v2<close> = test "v2"
end

function test2(name1,name2)
    return "string",test(name1),test(name2)
end

do -- 2. Is order of variables correct or changed? Programmer should always trace it.
   -- You can't specify <close> to normal variable only for table
   -- This is useless waste of energy
    local a,b<close>,c = test2("v3","v4")
end

function test3(...)
    return setmetatable( { test2(...) } , {
        __close=function(self)
            -- 3. how is intended to do recursive close ?
            print("group")
            for i=#self,1,-1 do -- again: sunset by hand
                local v=self[i]
                local mt=getmetatable(v)
                if mt and mt.__close then mt.__close(v) end
            end
        end
    })
end

do -- 4. There is no mechanism for recursive to-be-close
   -- Again it falls on the shoulders of users
    local r<close> = test3("v5","v6")
end

function test4(...) end

do -- 5. If result is not using or passed as arguments we will have leaks
   -- This again force to gain useless efforts
    test3("v7","v8")
    test4( test3("v9","v10") )
end

print "collect garbage"
collectgarbage "collect"

print "done"

--[[output:

Lua 5.4
__close v2
__close v3
group
__close v6
__close v5
__gc v8
__gc v7
__gc v6
__gc v5
__gc v4
__gc v3
__gc v2
__gc v1
collect garbage
__gc v10
__gc v9
done

]]

Variables are not automatically be closed. You have to trace this manually EVERY time. It's like manually coloring for variables. Any if any color doesn't match it will works not as expected. Absolutely pointless activity. It will be worse if code base will grow and number of programmers will increase. Any changes will cause pain every time they be applied.

More over every thing to manage resource lua has before version 5.4. One possible solution for resource management is

https://raw.githubusercontent.com/kov-serg/lua-aux/master/proto-seq_fn.lua

Have any reasonable objections?