Life of local variables in a module

  • From: Yin Zhu <zhuyin.nju@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 18 Mar 2017 18:01:59 +0800

Hi LuaJit List,

I am putting a few functions into a lua file, which is used as a module
(e.g., to be 'require'd in a script).

This module has a few local variable which are used in the functions. I am
not sure of the life time of these variables; will they be GC'ed when the
function refer to them?

As an example, the following lua file has buf as a local variable and buf
is used to store the output of a C function. I don't know when will LuaJit
will GC buf. Is it possible that when I call the Lua function myfun, the
local variable is GC'ed?

Thanks!

*modula_a.lua:*

ffi.cdef[[
void myfun(int input, char *buf, int bufsize);
]]

local buf = ffi.new('char[1024]')

local myfun = function(i)
   ffi.C.myfun(i, buf, 1024) -- call C function to get output in buf
   return ffi.string(buf)    -- convert buf to Lua string
end

return {  -- expose myfun, but not local variables
  myfun = myfun
}

Other related posts: