lgi-devs / lgi-devs/lgi

Signal callbacks prevents GC

Open
#55 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Lua
Stars
491
Forks
81
PR merge metrics
No merged PRs in 30d

Description

I bumped into the problem that setting callbacks for an lgi object appears to prevent any references from within the callback to be garbage collected.

My use case is this:

I have an object o containing a lgi object. For the lgi object I provide a signal handler; a closure that references said object o. This unfortunately seems to prevent any garbage collection of o. This is a problem since o and its siblings are dynamically created objects that could be created in any number during the applications lifetime, and that also have other resource cleanup tasks associated with GC. Any thoughts regarding this?

Below you'll find a self contained stripped down example of the problem:

local lgi = require('lgi')

local function gen()
  -- local a = { ref = {} } -- this works fine
  local a = { ref = lgi.Gtk.Entry() } -- but lgi objects does not
  a.callback = function() return a end
  a.ref.on_focus_in_event = a.callback
  return a
end

local cache = setmetatable({}, {__mode = 'v'})
cache[1] = gen()
collectgarbage()
assert(cache[1] == nil, "reference was not collected")

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The reproducer uses gen(), lgi.Gtk.Entry(), on_focus_in_event, the callback closure, and collectgarbage(); start by running it to confirm the retained reference. Trace the signal callback lifecycle and garbage-collection behavior. Done means cache[1] becomes nil after collectgarbage() while signal handling still works.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.