c++使用luabind示例
2016-07-25 11:39
465 查看
直接上代码
//main.cpp
//test.lua
//makefile
//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*
相关文章推荐
- Linux socket 初步
- 使用C++实现JNI接口需要注意的事项
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- 关于指针的一些事情