Advertisement

passing C++ object to lua function

Started by August 28, 2003 03:49 AM
1 comment, last by soehrimnir 21 years, 2 months ago
Hello, I am currently using tolua to be able to use a C++ class in lua. It all works fine and it's possible to create a object of this class by calling MyClass:new(). However, I wan't to be able to create the object in C++ and call a lua function from C++ while giving this object as a parameter.

// lua
function test(myclass)
  myclass:aMethod();
end

// c++
class MyClass
{
public:
  void aMethod() { cout << "Wow" << endl; }
};
  
So, before I call lua_pcall(....), I need to get the object onto the stack in some way. Anyone knows how? [edited by - soehrimnir on August 28, 2003 5:02:13 AM]
Well, I haven''t tried to implement this quite yet, but from studying the code generated by a tolua binding for a class new operator, here are my thoughts. (These are for Lua 4.0 and corresponding tolua; I haven''t played with Lua 5.0 yet.)

In new-operator bindings, tolua makes use of the tolua_pushusertype() function. It allocates a new object of the class, then uses tolua_pushusertype() to push it onto the stack. Seems like this would be a handy mechanism to use, if your class is already bound by tolua.

Here are some lines from a sample new binding from my game:

static int toluaI_EffectsBind_CombatEffect_new00(lua_State* tolua_S){...CombatEffect* toluaI_ret = (CombatEffect*)  new CombatEffect(); tolua_pushusertype(tolua_S,(void*)toluaI_ret,tolua_tag(tolua_S,"CombatEffect"));...} 


As long as you know the type name of your bound class (which is probably the name of the class to start with), to pass to the tolua_tag() function, it should be relatively easy to push an existing object onto the stack using pretty much this same method.

Josh
vertexnormal AT linuxmail DOT org

Check out Golem at:
My cheapass website
Advertisement
Thanks, that worked perfectly. Only when using lua5 and tolua5 you don''t need to do a call to tolua_tag() anymore. Now you can just provide the string right away.

This topic is closed to new replies.

Advertisement