[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua state as a C++ class ...
- From: "Alex Bilyk" <nebula-crl-2688@...>
- Date: Sat, 15 Jun 2002 02:33:43 -0700
----- Original Message -----
From: "Joshua Jensen" <jjensen@workspacewhiz.com>
To: "Multiple recipients of list" <lua-l@tecgraf.puc-rio.br>
Sent: Friday, June 14, 2002 1:25 AM
Subject: Re: Lua state as a C++ class ...
> >I have wrapped lua_State into a C++ class such that one can say
> >cLuaState ls;
> >However, I had to add a field to lua_State in order to be able to get
> to my
> >cLuaState from registered application functions written in C++.
> Needless to
>
> I recommend this (from my LuaState C++ code):
>
> class cLuaState
> {
> // This is the FIRST and ONLY member. NO virtual functions.
> lua_State* m_state;
> // Accessors...
> };
Yep, I ended up using this approach but the other way around. I added <void*
user_data> as the FIRST member in lua_State. And created my own structure to
use in C functions
struct cContext
{
cILua* mpLua;
};
This way <mpLua> maps right on <user_data>. If I didn't have to use virtual
fucntions, your way of doing it would be a better choice.
In Open() I say
L->user_data = static_cast<cILua*>(this); // 'this' is the implementation
bihind cILua interface
My C functions registered with LUA look like this
sint32 get_tos(cContext* pContext)
{
cILua* pLua = pContext->mpLua;
pLua->PushNumber(pLua->GetTop());
return 1;
}
cILua is nothing but a bag of pure virtual functions with no data members.
AB
>
> typedef int (*cLuaStateCFunction)(cLuaState state);
>
> void cLuaState::Register(const char* funcName, lua_CFunction function)
> {
> lua_pushstring(m_state, funcName);
> lua_pushcclosure(m_state, (lua_CFunction)function, 0);
> lua_settable(m_state, m_stackIndex);
> }
>
> void cLuaState::Register(const char* funcName, cLuaStateCFunction
> function)
> {
> lua_pushstring(m_state, funcName);
> lua_pushcclosure(m_state, (lua_CFunction)function, 0);
> lua_settable(m_state, m_stackIndex);
> }
>
> Works like a charm:
>
> static int MyCallback(cLuaState state)
> {
> state.whatever();
> return 0;
> }
>
>
> state.Register("MyCallback", MyCallback);
>
> -Josh
>