利用lua-intf来调用C++函数

来源:互联网 发布:在线网页源码获取 编辑:程序博客网 时间:2024/06/17 12:30

利用lua-intf来调用C++函数

这里主要是在windows利用VS2015完成,首先是配置lua环境,包含lua的头文件,连接器里面链接lua的静态库,然后就是包含lua-intf的代码,具体如下表



需要注意的是lua-intf_d6f17a是一个包含lua-intf的目录。

lua-intf的代码在github上可以下载:https://github.com/SteveKChiu/lua-intf

如何使用看他的README.md

这里我们主要是测试绑定C++类中的函数,工程目录结构如下


main.cpp代码如下

#include <iostream>#include <lua.hpp>#include <LuaIntf/LuaIntf.h>#include <string>const char SCRIPTS_DIR[] = "../scripts";using namespace std;struct lua_State;class TestLog{public:static TestLog *getInstance(){static TestLog instance;return &instance;}~TestLog();void Log(const string &str);void BindLua(lua_State *l);private:TestLog();};TestLog::TestLog(){}TestLog::~TestLog(){}void TestLog::Log(const string &str){cout << str << endl;}namespace{using LuaRef = LuaIntf::LuaRef;void LuaLog(const string &str){TestLog::getInstance()->Log(str);}namespace LuaTestLog{void Bind(lua_State* L){assert(L);LuaIntf::LuaBinding(L).beginModule("c_testlog").addFunction("log", &LuaLog).endModule();}};};void TestLog::BindLua(lua_State *l){LuaTestLog::Bind(l);}int main(){lua_State *l = luaL_newstate();luaL_openlibs(l);TestLog::getInstance()->BindLua(l);cout << "mmmmmmmmmmm" << endl;luaL_dofile(l, "test.lua");system("pause");return  0;}

log.lua代码如下:

local Log = {}local log = c_testlog.logfunction Log:new(log_name)assert("table" == type(self))assert(not log_name or "string" == type(log_name))local log = {}log.log_name = log_name or "Log"setmetatable(log, self)self.__index = selfreturn logendfunction Log:set_log_name(log_name)self.log_name = log_nameendfunction Log:info(pattern, ...)log(string.format(pattern, ...))endfunction Log:debug()    print("ssssssssssssssssssssssssss")endreturn Log

test.lua代码如下:

local function main()    print("dddddddddddddddddddddddd")    local p = "../testLuaIntf"    package.path = package.path ..";" .. p .. "/" .. "testLuaIntf" .. "/?.lua"    --package.path = package.path .. "E:\VSProject\?.luac"    print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb")    local log = require("log"):new("svn_log")    log:info("%d...",1)    --:new("svc_log")    print("ssssssssssssssssssssssss")end xpcall(main,function(...)local msg = {...};for k ,v in pairs(msg) do print("k="  .. tostring( k)  .. " v=" ..  tostring(v))endprint(tostring() .. " 123")end)

这里流程通过C++调lua的接口luaL_dofile(l, "test.lua");来执行test.lua,test.lua中require("log"),然后lua再调用C++的函数Log完成打印