使用LuaBridge导出容器类

问题描述

我想将SRect和SRectVector从C ++导出到Lua,但是编译失败。 正确的做法是什么? 编译器:vs2019,vc ++ 11 操作系统:Win10 64

Push()遇到编译错误

我认为参数只是SRectVector *,为什么编译器认为它是'std :: vector >'?

    class SRect{
    public:
        int left;
        int top;
        int right;
        int     bottom;
        SRect(int l,int t,int r,int b)
            : left(l),top(t),right(r),bottom(b){}
        //...
    };
    
    typedef std::vector<SRect>    SRectVector;
    
    luabridge::getGlobalNamespace(L)
        .beginClass <SRect>("SRect")
            .addConstructor <void(*) (int,int,int)>()
            .addProperty("left",&SRect::left)
            //...
        .endClass()
        .beginClass <SRectVector>("SRectVector")
            .addFunction("Push",std::function <void(SRectVector*,const SRect&)>(
                    [](SRectVector* vec,const SRect& rc) { (*vec).push_back(rc); }))
            //...
        .endClass()
    .endNamespace();
    
    ```
    
1>E:\Code\include\LuaBridge/detail/TypeList.h(177): error C2664: 'luabridge::detail::TypeListValues<luabridge::detail::TypeList<Param,luabridge::detail::TypeList<const SRect&,luabridge::detail::MakeTypeList<>::Result>>>::TypeListValues(luabridge::detail::TypeListValues<luabridge::detail::TypeList<Param,luabridge::detail::MakeTypeList<>::Result>>> &&)': cannot convert argument 1 from 'std::vector<SRect,std::allocator<_Ty>>' to 'Head'
1>        with
1>        [
1>            Param=SRectVector *
1>        ]
1>        and
1>        [
1>            _Ty=SRect
1>        ]
1>        and
1>        [
1>            Head=SRectVector *
1>        ]
1>E:\Code\include\LuaBridge/detail/TypeList.h(179): note: No user-defined-conversion operator available that can perform this conversion,or the operator cannot be called
1>E:\Code\include\LuaBridge/detail/TypeList.h(176): note: while compiling class template member function 'luabridge::detail::ArgList<Params,1>::ArgList(lua_State *)'

解决方法

更多挖掘之后,我找到了原因。完整的用户定义类可以轻松导出。但是容器指针没有。添加此类代码后,编译正常,

namespace LuaBridge
{
    template <>
    struct Stack <SRectVector*>
    {
        static void push(lua_State* L,SRectVector* ptr)
        {
            SRectVector** pp = (SRectVector**)lua_newuserdata(L,sizeof(SRectVector*));
            *pp = ptr;
        }

        static SRectVector* get(lua_State* L,int index)
        {
            return (SRectVector*)lua_touserdata(L,index);
        }
    };
}

或添加一个更通用的

template <class T>
struct Stack <std::vector<T>*>
{
    typedef typename std::vector<T>* ContainerPointerType;

    static void push(lua_State* L,ContainerPointerType ptr)
    {
        ContainerPointerType* pp = (ContainerPointerType*)lua_newuserdata(L,sizeof(ContainerPointerType));
        *pp = ptr;
    }

    static ContainerPointerType get(lua_State* L,int index)
    {
        return (ContainerPointerType)lua_touserdata(L,index);
    }
};
,

请勿包含,然后解决此问题。