C++利用LuaIntf调用Lua
本文主要介绍了C++利用LuaIntf调用Lua的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
void LuaTest::OnResponse(uint32_t uLuaRpcId,
const std::string& sRespContent) const
{
using LuaIntf::LuaRef;
LuaRef require(m_pLuaState, "require");
try {
LuaRef handler = require.call<LuaRef>("client_rpc_response_handler");
handler.dispatchStatic("handle", uLuaRpcId, sRespContent);
}
catch (const LuaIntf::LuaException& e) {
std::cerr << "Failed to call lua client_rpc_response_handler.handle(), "
<< e.what() << std::endl;
}
}
这是测试客户端代码,可以写Lua代码测试服务器.
Lua代码中发出一个Rpc请求时, 会在Lua中保存一个回调, 待收到应答时触发回调. 通过uLuaRpcId来索引该回调.
sRespContent 是收到的应答包, 将在lua中解包.
OnResponse() 就是调用了 Lua 代码:
require("client_rpc_response_handler").handle(uLuaRpcId, sRespContent)
利用lua-intf来调用C++函数
这里主要是在windows利用VS2015完成,首先是配置lua环境,包含lua的头文件,连接器里面链接lua的静态库,然后就是包含lua-intf的代码,具体如下表

需要注意的是:lua-intf_d6f17a是一个包含lua-intf的目录。
lua-intf的代码在github上可以下载:https://www.easck.com/p>
这里我们主要是测试绑定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;
}










