当前位置: 首页 > 工具软件 > LuaBind > 使用案例 >

c++使用luabind示例

甄阿苏
2023-12-01

直接上代码


//main.cpp

#include <iostream>
#include <lua.hpp>
#include <luabind/luabind.hpp>

extern "C"
{
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}

bool LoadScript(lua_State* L, const std::string& fname)
{
    if (luaL_dofile(L, fname.c_str()))
    {
        std::cerr << lua_tostring(L, -1) << std::endl;
        return false;
    }

    return true;
}

class NumberPrinter
{
public:
    NumberPrinter(int number) : m_number(number)
    {

    }
    NumberPrinter()
    {
        m_number = 100;
    }
    void printNum()
    {
        std::cout << "C++ printNum" << std::endl;
        std::cout << m_number << std::endl;
    }

private:
    int m_number;

};

int main(int argc, char* argv[])
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    luabind::open(L);

    luabind::module(L)
    [
        luabind::class_<NumberPrinter>("NumberPrinter")
        .def(luabind::constructor<int>())
        .def("printNum", &NumberPrinter::printNum)
    ];

    LoadScript(L, "test.lua");

    luabind::object tobj = luabind::globals(L)["Game"];
    if (luabind::type(tobj) == LUA_TTABLE)
    {
        NumberPrinter np1(100);
        luabind::call_member<void>(tobj, "enter", &np1);
    }   

    luabind::object tobj2 = luabind::globals(L)["NumberPrinter"];
    if (luabind::type(tobj2) == LUA_TTABLE)
    {
        luabind::call_member<void>(tobj2, "enter");
    }

    lua_close(L);
}


//test.lua
print("BEFORE", _G["NumberPrinter"])

---[[
local meth = {}
meth.__index = meth

local tbl = {}
setmetatable(tbl, meth)

_G["NumberPrinter"] = tbl
print("AFTER", _G["NumberPrinter"])
--]]


---[[
function NumberPrinter:printNum()
    print("printNum")
end
--]]

--[[
p1 = NumberPrinter(1000)
p1:printNum()
--]]

--NumberPrinter:printNum()

function NumberPrinter:test()
    print("THIS IS A TEST")
end

NumberPrinter:test()

function NumberPrinter:enter()
    print("THIS NUM ENTER")
end


Game = {}

function Game:enter(np)
    print("THIS IS ENTER")
    print("USE", _G["NumberPrinter"])
    np:printNum()
end

//makefile

test:main.o
	g++ main.cpp -o test -I../base/xlib/ -L/usr/lib64/ -llua -ldl -lluabind
clean:
	rm -rf *.o
	rm -rf test
	rm -rf core*
clear:
	rm -rf core*




 类似资料: