lua-users home
lua-l archive

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


Gang,

Just wanted to share my own 2 cents on the less-than-ideal way I happened to choose to implement my C++/Lua Object Oriented programming integration...

I have my C++ objects.
I use userdata to have these c++ object cross-over into lua-land.
These userdatas have metatables so that methods of my C++ object can be called from lua so scripts.

All was good up until I decided to allow scripts to create new fields in the userdata objects.

Let me explain: Say I have a sprite C++ object with two intrinsic data fields: location and visibility. From lua via the metatable on the userdata a script can do things like sprite:SetVisibility(..) or sprite:OffsetLocation(...) and so on.

But I then needed the flexibility for scripts to add their own fields for the script's own use: sprite.isTankSprite = true

To do this, I have had to go through some unfortunate hoops. I now have a global table that can contain a custom table for each of my userdata's. I intercept the newIndex call to create a secondary table and replicate the variable being created in the table. Then have to in the index call of the metatable also search the global table for a custom table that corresponds to the userdata and if its there, search it.

I of course also have to worry about watching for the deletion of the userdata and dispose of its associated custom table...

Definitely a pretty nasty corner I painted myself into. It's too late to change now (and it all works well so far), but had I this insight I probably would have just had my C++ objects have a table representing them with what's currently in the userdata memory directly in the table (it's only a ptr to the actual C++ object)...

Thought I'd share my situation with everyone just in case it helps anyone else thinking of heading down similar paths...

ando "wish I had Programming in Lua before I dove in" sonenblick
-----------------------
Ando Sonenblick
SpriTec Software
www.spritec.com