Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua - late call of class destructor

I am working on a c++ program which essentially just executes a lua script. In that lua script however classes are constructed, which have been exported from my c++ program to the lua script.

My main() c++ function just calls after some preparations...

    luabind::call_function<void>(m_L, "main");

Now my lua script looks like this

local function test()
local c = C()
end

function main()
    for i=1,2 do
        log(i)
        test()
    end
end

I have included a std::cout << "destructor" << std::endl; in C's destructor so I know when it is called. I would expect that lua's garbage collection calls the destructor of c everytime execution of test() ends, because that is when it falls out of scope. Instead I see the following output:

1
2
destructor
destructor

rather than

1
destructor
2
destructor

Does anyone have an idea why this is? Am I missing something here?

like image 546
chris.schuette Avatar asked Feb 20 '23 20:02

chris.schuette


1 Answers

I would expect that lua's garbage collection calls the destructor of c everytime execution of test() ends, because that is when it falls out of scope.

This is not the case. Lua's garbage collection does not run at the end of every scope. It is typical of garbage collected languages that you can't depend on when exactly the destructors are run, and in some languages an object may never be destroyed at all.

There is not any way to make Lua automatically destroy objects deterministically like C++ does.

If you have to depend on this then you may be able to get by with Lua's collectgarbage function, however it would probably be better to simply change your expectations and redesign accordingly.

Here's the Lua documentation on how their garbage collection works.


An example of using collectgarbage:

local function test()
    local c = C()
end

function main()
    for i=1,2 do
        log(i)
        test()
        collectgarbage "collect"
    end
end
like image 138
bames53 Avatar answered Feb 27 '23 21:02

bames53