[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: LUA <--> C++ question
- From: "Ashley Fryer" <lua@...>
- Date: Wed, 15 Mar 2000 07:01:38 -0800
> I would like to enable communication between LUA and C++ classes. I don't
> want to use "tolua" or any other tool.
>
> Considere the following code, do you think these is a good way (or almost
> quite right) or do you think I was lucky not to have test.exe crashing ?
> Is there a way to simplify the whole operation ?
I use a similar approach in my code. If you plan to use polymorphism, I
suggest you implement a common base class for all of your lua-enabled C++
classes. Then make sure you always cast to the base class before
lua_pushuserdata.
Example:
class Scripted {};
class MyFoo : public Scripted {};
...
MyFoo my_foo;
lua_pushuserdata( static_cast< Scripted * >( & my_foo ) );
...
This also makes it possible to use dynamic_cast when you're going in the
other direction:
Scripted * my_scripted = (Scripted*)lua_getuserdata(lua_getparam(1));
MyFoo * my_foo = dynamic_cast< MyFoo * >( my_scripted );
if( my_foo )
{
// yes, we really have a MyFoo object...
}
These techniques will help you avoid some subtle bugs resulting from casts,
especially if any of your classes use multiple inheritance.
Other possibilities... you could implement a class with overloaded insertion
operators as syntactic sugar for the lua_pushXXX functions. Then you could
do this:
LuaStack() << my_num << my_string;
Instead of:
lua_pushnumber( my_num );
lua_pushstring( my_string );
ashley