lua-users home
lua-l archive

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


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Michael Newberry wrote:
[...]
> 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 );

You don't need to return two things. What you're trying to do here is to
create an object and *also* create an object containing the address of
the object, which is unnecessary and is just causing complications. You
only need to return the userdata itself.

The usual way of solving this sort of problem is:

1. Create C-side object.
2. Create a userdata 4 bytes long.
3. Put point to C-side object in userdata.
4. Set userdata's metatable to something with a __gc method.
5. Return userdata.

Note that this isn't using lightuserdatas *at all*!

Typically this boils down to about four lines of code. Now you're only
returning one thing, your Lua-side code is much simplified, and there's
much less scope for horrible bugs (such as losing track of your
userdata, causing it to be garbage collected, causing the C-side object
to be freed, causing the address in the lightuserdata to become bogus.
Which is bad.

- --
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ "People who think they know everything really annoy those of us who
│ know we don't." --- Bjarne Stroustrup
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iD4DBQFKiGTSf9E0noFvlzgRAvGxAJ4izJ+87CQ0zueX3dRSzF1ITfP4OgCYkoHU
UqG7u+zfa2Pridzb/EjN+g==
=QSUL
-----END PGP SIGNATURE-----