Skip to content

Instantly share code, notes, and snippets.

@CapsAdmin
Last active February 28, 2024 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CapsAdmin/2edde2741e7715a9d64c597ed2d9b139 to your computer and use it in GitHub Desktop.
Save CapsAdmin/2edde2741e7715a9d64c597ed2d9b139 to your computer and use it in GitHub Desktop.
local ffi = require("ffi")
ffi.cdef("typedef struct { int *a; } foo_t;")
local function force_gc()
-- silly way to force collection
for i = 1, 10000 do
collectgarbage()
end
end
do -- WRONG
local s = ffi.new(
"foo_t",
ffi.new("int[4]", 1, 3, 3, 7) -- this temp value can get garbage collected from this point on
)
force_gc()
local buf = {}
for i = 0, 3 do
buf[i + 1] = s.a[i]
end
print(table.concat(buf) == "1337")
end
do -- WRONG
local function get_s()
local a = ffi.new("int[4]", 1, 3, 3, 7)
local s = ffi.new("foo_t", a) -- 'a' can get garbage collected from this point on
return s
end
local s = get_s()
force_gc() -- [[ here ]]
local buf = {}
for i = 0, 3 do
buf[i + 1] = s.a[i]
end
print(table.concat(buf) == "1337")
end
do -- WRONG
local function get_s()
local a = ffi.new("int[4]", 1, 3, 3, 7)
local s = ffi.new("foo_t", a)
return a, s
end
local a, s = get_s() -- 'a' can get garbage collected from this point on as it's never used
force_gc()
local buf = {}
for i = 0, 3 do
buf[i + 1] = s.a[i]
end
-- 'a' can get garbage collected from this point on
print(table.concat(buf) == "1337")
end
do -- OK
local function get_s()
local a = ffi.new("int[4]", 1, 3, 3, 7)
local s = ffi.new("foo_t", a)
return a, s
end
local a, s = get_s()
_G.TEMP_A = a
force_gc()
local buf = {}
for i = 0, 3 do
buf[i + 1] = s.a[i]
end
TEMP_A = nil
-- 'a' can get garbage collected from this point on
print(table.concat(buf) == "1337")
end
do -- OK
local function get_s()
local a = ffi.new("int[4]", 1, 3, 3, 7)
local s = ffi.new("foo_t", a)
return {__a = a, s = s}
end
local s = get_s()
force_gc()
local buf = {}
for i = 0, 3 do
buf[i + 1] = s.s.a[i]
end
-- 's.s.a' can get garbage collected from this point on
print(table.concat(buf) == "1337")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment