lua-users home
lua-l archive

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


[...]

Sorry, Michael, I thought you said you'd be binding code into lua for years.

Yes, I have, for almost 15 years. But I've never dealt with userdata before now.

Your code ends with pushlightuserdata(), then does "return 1". So, it
is returning only 1 thing, and that thing is not the userdata you'd
created earlier.

A userdata is just another Lua object type, like a lightuserdata. So
just push it onto the stack and return it. You don't need to use
lightuserdatas at all.

I already did what you describe. The CFunction that creates the userdata is named CreadeData(). After creating the C++ object, it returns 2 parameters: the C++ object pointer and the userdata. It ends like this:

   lua_pushlightuserdata( L, pData );

   luaL_getmetatable( L, "CData_type" );

   return 2;

The __gc metamethod I registered for this kind of userdata is created and it has the correct pointer for the pData object (which I test using luaL_checkudata()).

BUT... that __gc CFuntion is being called by lua *immediately* after the return from the above code. The lua calling code is like this:

   self.ptr, self.pUserData = CreateData()

Why is it the __gc being done immediately? This is what I was talking about when I asked about the carbage collector "What defines being "used" by lua?" For some reason, lua believes it is time for this userdata to be deleted. Why?


Basically:

lightuserdata: 4 bytes only, no metatable, no notification when GCd

userdata: any number of bytes, metatable, notification when GCd

Check out the example here: http://www.lua.org/pil/28.1.html

The fundamentals of this are covered in the above, and the succeeding
chapters which cover __gc (and I also posted a link to), and explained
much better than I can.

If are comfortable in C, and sit down and spend a few hours reading
carefully through those chapters, and write a small example to start
with, then build up, you should be OK.

I've read that stuff over and over. That's why I said something just is not clicking.

Michael


Cheers,
Sam