如何向LuaBridge添加类函数?

时间:2019-06-30 08:09:57

标签: c++ lua luabridge

在我的类中为Lua初始化函数的函数中,我想从类本身实现函数的注册,并且将对每个实例分别执行该注册,也就是说,它不是静态的,但是我不知道如何,请告诉我该怎么做。这是我的课-

//.h
#pragma once

#pragma comment(lib, "lua53.lib")
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

#include <iostream>
#include <LuaBridge/LuaBridge.h>
using namespace std;
using namespace luabridge;
#define SAFE_DELETE(x) { if(x) delete x; x = nullptr; }
class Lua_sup
{
private:

    string m_name;
    lua_State* L ;
    bool init_state = false;
    vector<string> draw;
public:
    Lua_sup(string name);
    Lua_sup() {};
    ~Lua_sup();
    bool init();
    bool test();
    lua_State* get_lua_state() { return L; }
    bool get_state() { return init_state; }
    void register_callback(string type, string name);
};

class vector2d
{
private :
    int m_x;
    int m_y;
public :

    vector2d() {        m_x = 0; m_y = 0;   }
    vector2d(int x,int y) { m_x = x; m_y = y; }
    int get_x() { return m_x; }
    int get_y() { return m_y; }

    void set_x(int x) { m_x = x; }
    void set_y(int y) { m_y = y; }
};
//.cpp
#include "Lua_sup.h"


Lua_sup::Lua_sup(string name)
{
    m_name = name;
    L = luaL_newstate();
    luaL_openlibs(L);
}


Lua_sup::~Lua_sup()
{


    lua_close(L);

}

void Lua_sup::register_callback(string type, string name) {
    cout << "print = " << type << endl;
    if (type == "draw")
    {
        draw.push_back(name);
    }
}
bool Lua_sup::init()
{
            try
    {

        getGlobalNamespace(L).addFunction("register_callback", register_callback); // Функцию которую я хотел бы добавить

    if (luaL_loadfile(L, m_name.c_str()) || lua_pcall(L, 0, 0, 0))   {

        cout << "Error";

        return 0;
    }


    init_state = true;






    getGlobalNamespace(L) 
        .beginClass<vector2d>("vector2d") 
        .addConstructor<void(*)(void)>() 
        .addConstructor<void(*)(int x,int y)>()
        .addFunction("get_x", &vector2d::get_x)
        .addFunction("get_y", &vector2d::get_y) 
        .addFunction("set_y", &vector2d::set_y)
        .addFunction("set_x", &vector2d::set_x) 

        .endClass(); //end class


    return 1;
    }
    catch (exception &e) {
        cout << e.what();
        return 0;
    }

    catch (...) {
        cout << "Unknown error";
        return 0;
    }


}

0 个答案:

没有答案