Home > 未分类 > Extensions to Luna to support userdata as return values from a lua-c call

Extensions to Luna to support userdata as return values from a lua-c call

As a helper to Lua-C interops, Luna is pretty small and elegant without fucking usage of boost or python.
But there seems to be no support for userdata ( such as a C class pointer, witch will be used in lua ) as return values from a c function. So we made a bit extension.

With a public member function "push_userdata":

    static void push_userdata(lua_State *L, T* pT) {
        userdataType *ud =
            static_cast<userdataType*>(lua_newuserdata(L, sizeof(userdataType)));
        ud->pT = pT;
        luaL_getmetatable(L, T::className);
        lua_setmetatable(L, -2);
    }

and a macro

#define PUSH_USERDATA(ClassName, LuaState, UserDataPtr) Luna<ClassName>::push_userdata(LuaState, UserDataPtr);
#define DECL_SCRIPT_METHOD(FunctionName) int FunctionName(lua_State* L)
#define IMPL_SCRIPT_METHOD(ClassName, FunctionName) int ClassName::FunctionName(lua_State* L)

So we can use that:

//in .h
class B;
class A {
    B* m_pB;
public:
    B* GetB() { return m_pB; }

    DECL_SCRIPT_METHOD( GetB );
};

//in .cpp

IMPL_SCRIPT_METHOD(A, GetB)
{
    PUSH_USERDATA(A, L, this->GetB())
    return 1;
}

It seems working correctly. A new user data is created once the method is called from lua.
I’m doubtting if there are safety or efficiency problems with this implementation. Farther tests are taking on and hope your advise 🙂

Advertisements
Categories: 未分类
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: