c++使用luabind示例

来源:互联网 发布:人海战术 知乎 编辑:程序博客网 时间:2024/05/22 04:38

直接上代码


//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 = methlocal tbl = {}setmetatable(tbl, meth)_G["NumberPrinter"] = tblprint("AFTER", _G["NumberPrinter"])--]]---[[function NumberPrinter:printNum()    print("printNum")end--]]--[[p1 = NumberPrinter(1000)p1:printNum()--]]--NumberPrinter:printNum()function NumberPrinter:test()    print("THIS IS A TEST")endNumberPrinter:test()function NumberPrinter:enter()    print("THIS NUM ENTER")endGame = {}function Game:enter(np)    print("THIS IS ENTER")    print("USE", _G["NumberPrinter"])    np:printNum()end

//makefile

test:main.og++ main.cpp -o test -I../base/xlib/ -L/usr/lib64/ -llua -ldl -lluabindclean:rm -rf *.orm -rf testrm -rf core*clear:rm -rf core*



0 0
原创粉丝点击