Get lua_State from inside dynamic class?

Started by
2 comments, last by Prozak 13 years, 7 months ago
So I have a class that is dynamically created from within a LUA script.

What I need is to call a certain LUA script function from within that same C++ class.

But the C++ class doesn't have a lua_State. So how do I get the lua State of the lua script calling the class' methods?

Thanks for any tips on this...
Advertisement
Let me elaborate a bit on this.

Using LuaBind I've bound a C++ class, so that a LUA script can create instances of that class.

But I need to call lua functions from those same C++ classes that are created dynamically.

So how do I go about doing that? I guess I need the lua_State...

I'm currently looking into the "raw" keyword in luabind, but I'm totally lost here...
Easiest way is to have a single, globally accessable lua state.

I use the following method that I quite like for such classes (you'll need to make a wrapper around the lua state) as in Game Programming Complete.

class A;static A* instance = NULL;class A{   A(bool global = false)   {      if(global)      {         instance = this;      }   }   ~A()   {      if(this == instance)      {         instance = NULL;      }   }   static A* GetInstance()   {      // Some error checking to ensure it exists      return instance;   }};


I like this method as it allows an object to be globally accessable just like a global/singleton but ultimately the object is owned by something and gets cleared away neatly (Providing you destruct objects in reverse order you create them). You can still then have single objects of the type without them being global.

The other option is to hvave a variable in your lua that is a pointer to the state itself and then pass that object in when you construct objects (might be better if you use multiple states). I find it nicer to use one single state and simple short use ones if I need to do soemthing like read some initialisation variables.

create new lua_State
set a global variable "this_state" to be th state you just created
When creating objects that need that lua_state in lua:
obj = Obj(this_state);

Interested in Fractals? Check out my App, Fractal Scout, free on the Google Play store.

Solved this using the raw keyword provided by luabind:
Quote: module( l->L ) [
class_<classMy>("classMy")
.def(constructor<>())
.def("Create", &lc_DlgControl::Create, raw(_2) )
];

When I call the "Create" method of the liaison class, it passes the lua state as part of the parameters. Here is it:
Quote: void Create( lua_State * pL )
{
[...code...]
};


Notice that "raw" is used with parameter "_2". That's because the first parameter is for the "this" keyword of the class.

This topic is closed to new replies.

Advertisement