lua-users home
lua-l archive

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


On Thu, Sep 3, 2020 at 7:18 PM 云风 <cloudwu@gmail.com> wrote:

> It’s incorrect because the object foo is on the stack and we can’t use &foo after foobar() returns.
> I think the point is that the lifespan of lua function foobar’s stackframe (slot #1) is longer than C stackframe of foobar.

Your analysis is right, but the problem is caused by putting a pointer
to a stack allocated object ( & foo ) inside what is equivalent to a
heap allocated one ( the table ), and not managing your objects right.
You may need to do it, in which case your solution is probably the
correct one, but the sample smells fishy. Normally when you need to do
this things you pcall() ( or try catch or whatever ) as soon as you
put the pointer inside the heap object, clear it as soon as pcall
returns and make the "destructor" check for pointer nullness or a
similar thing.

It's like doing:
struct foo;
struc x {
   foo * f;
   x(foo * _f): f(_f) {}
   ~x() { do_something(f); }
}
x* a() {
  foo f;
  return new x(&f);
}
x * z = a();
You may need to do that, but it does not look right, x needs to get
foo from someone which ignore proper lifetimes, and you are not
insuring it.

The classic way for this would be to allocate the foo with malloc,
store its lightuserdata in the table ( so it controls the ownership )
and make the close method test, call the exit func and free.

Or more luaesque, allocate foo inside a full userdata, store that in
the table and let lua free it after close automatically.

Francisco Olarte.