C++中调用Lua的全局变量和全局函数

lua代码

a = 0

str = "hello world"

function SetA(param)
    a = param
end

function SetStr()
    str = "hello wolrd ni hao"
end

c++使用前需要包含头文件

#include <lua/lua.hpp>
#include <luabind/luabind.hpp>
#include <luabind/raw_policy.hpp>
lua_State* m_L = lua_open();
luaL_openlibs(m_L);
luabind::open(m_L);
try
{
    //获取lua中的全局变量a
    luabind::object luaRet = luabind::globals(m_L)["a"];
    int a = luabind::object_cast<int>(luaRet);

    //修改lua中的全局变量a的值为10
    luabind::globals(m_L)["a"] = 10;

    //获取全局变量str
    luaRet = luabind::globals(m_L)["str"];
    std::string b= luabind::object_cast<std::string>(str);

    //修改lua中的全局变量str的值为”ni hao"
    luabind::globals(m_L)["str"] = "ni hao";

    //调用lua中的全局函数SetA()
    luabind::call_function<int>(m_L,"SetA",10);

    //调用lua中的全局函数SetStr()
    luabind::call_function<void>(m_L,"SetStr");
}
catch (std::exception& e)
{
    theLog.error("Lua runtime error: %s", e.what());
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值