awesome/tests/test-use-after-gc.lua
Uli Schlachter 489aa4dc24 Improve behaviour of GC'd objects
Before this commit: When we are GC'ing an object, we clear its metatable, since
otherwise crashes could occur in various places. This means that if someone
tries to use such an object, they get an unhelpful error message like "attempt
to index userdata object" and they don't understand what the problem is. Also,
this means that foo.valid does not actually work after GC.

This commit changes this behaviour. Instead of setting an empty metatable, we
now create a metatable with an __index and __newindex method. These metamethods
produce better error messages that they sat the underlying object was already
garbage collected. Better yet, the __index metamethod makes foo.valid be false
instead of causing an error, so that the existing machinery for detecting
invalid objects continues to work.

This commit also adds a functional test that verifies this behaviour.

Signed-off-by: Uli Schlachter <psychon@znc.in>
2016-09-24 14:37:07 +02:00

31 lines
776 B
Lua

-- Test behaviour of C objects after they were finalized
local runner = require("_runner")
local done
do
local obj
local func = function()
assert(obj.valid == false)
assert(not pcall(function()
print(obj.visible)
end))
assert(not pcall(function()
obj.visible = true
end))
done = true
end
if _VERSION >= "Lua 5.2" then
setmetatable({}, { __gc = func })
else
local newproxy = newproxy -- luacheck: globals newproxy
getmetatable(newproxy(true)).__gc = func
end
obj = drawin({})
end
collectgarbage("collect")
assert(done)
runner.run_steps({ function() return true end })
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80