Advertisement

luaBind + Class

Started by August 02, 2004 11:23 PM
5 comments, last by Krun 20 years, 3 months ago
Hi, I'm trying to expose a function from a class to LUA. I know what you're going to say, but keep reading...I have a class called CObjects like this:

class CObject
{
  int GetX() { return 5; }
};

CObject Door;
ok, and I want to expose Door.GetX() to lua as just GetDoorX(). I've tried def( "GetDoorX", &Door.GetX ), but that didn't work. So my question is how do I do this? Is it possible? Denny.
I'm pretty new to LUA myself, so please forgive me if I'm getting it wrong. I'm not sure that you can expose methods in this way, given that LUA is based in C, while your method is C++.

I think a way around it would be something like

class CObject{  int GetX() { return 5; }};CObject Door;static int GetDoorX(lua_State *L){   lua_pushnumber(L,Door.GetX());   return 1; // 1 paramater returned}int main(){   /* ... */   lua_register(L, "GetDoorX", GetDoorX);   /* ... */}


I'm sure that there are other/better ways of doing this. I'm no expert, but I think that this will work.
Advertisement
I think he is trying to use luabind, in which case he would do something like this:

	module ( luaState )	[		class_< COBject > ( "CObject" )			.def (constructor<>())		        .def ( "GetX", &CObject::GetX )	]


If, however, you are not trying to use luabind to expose your class, Stagz method should work.
Quite right, I didn't realise that luabind was different to lua. I told you I was a newb didn't I :)
yeah, I should have put that luabind stuff in there somewhere. But I don't want to expose the class to LUA. I don't want the user to creat anymore objects of that type. I think I figured it out anyway. I have to create a wrapper function.

class CObject{  int GetX() { return 5; }};CObject Door;int luabind_Wrapper_Door_GetX(){  return Door.GetX();}module( L )[  def( "GetX", &luabind_Wrapper_Door_GetX );];


This works, and seems to be a good solution.

Thanks anyway,

Denny.
Quote: Original post by brain21
yeah, I should have put that luabind stuff in there somewhere. But I don't want to expose the class to LUA. I don't want the user to creat anymore objects of that type. I think I figured it out anyway. I have to create a wrapper function.


I'm no luabind expert, but if you don't want your class to be instantiated can't you just not bind the constructors?

module(l)[class_<CObject>("CObject").def("GetX", &CObject::GetX)];
Advertisement
You have to use wrapper functions for those kinds of calls. It would be imposible to expose a member function directly.

This topic is closed to new replies.

Advertisement