lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, May 30, 2019 at 6:57 PM Roberto Ierusalimschy wrote:
> > I believe that many programmers stumble upon this while learning Lua.
>
> Well, it is a very strange thing to hit, you need to do some weird
> things, starting by clearing the "local" which holds it inside the
> function.

It is weirded than that. You also need some alternative way to access
the value that is being collected.
That doesn't seem common for someone learning Lua.



You're correct about "the alternative way".
But nevertheless, such mistake could be made while learning Lua.
And I believe many people do this mistake (I've done it too).
A programmer must understand that Lua doesn't anchor function's arguments.
Otherwise he could write a program similar to the following:

   local ffi = require"ffi"
   ffi.cdef"int MessageBoxA(void*, const char*, const char*, int)"

   local function show_message(str, cap)
      str = ffi.cast("const char *", str)
      cap = ffi.cast("const char *", cap)

      -- add some code here which may trigger GC

      ffi.C.MessageBoxA(nil, str, cap, 0)
   end

   show_message("Hello "..os.getenv"USERNAME", "Greeting")



Here FFI library is used to create cdata (specific type of userdata) which contains references not visible by GC.
New value of local variable 'str' is actually a C pointer to Lua string passed as argument.
For this pointer to be valid, original Lua string must exist.
But in this program 'str' may become a dangling pointer before 'MessageBoxA' is invoked.

The situation is tricky enough.
The mistake is observable only when Lua string is dynamically created (such as "Hello "..username).
Strings represented as literals (such as "Greeting") are anchored by the function's prototype, so they will not be GC-ed inside this function.

Of course, this problem is not FFI-library specific.
You can make similar mistake when using usual userdatum.
FFI library just gives you wonderful possibility to create userdata-like objects without writing C code.

That's why I've suggested to add phrase to the Lua manual to emphasize the fact that Lua doesn't anchor functions' arguments.