luabind常用方法总结

转自  http://blog.csdn.net/caoyanting007/article/details/5709820

 

 

luabind比较复杂,功能包罗万象,但使用起来比较简单,特别是最常用的方法只有几个,下面结合一个简单的例子总结一下。

    在我们游戏应用中,一般都是已c++为主导的,也就是说c++主动调用lua脚本。
 
先写一个比较常见的lua脚本:
 
nGlobal = 10 --一个全局的整形变量 
strGlobal = "hello i am in lua" --一个全局的字符串变量 
--一个返回值为int类型的函数 
function add(a, b) 
return a+b 
end 
--一个返回值为string类型的函数 
function strEcho(a) 
print(a) 10 
return 'haha i have print your input param' 
end 
cppapi.testFunc() --调用c++暴露的一个测试函数 
t={name='ettan', age=23, desc='正值花季年龄'}

 

 

lua脚本结束
 
下面写c++函数中的调用了
 
#include<iostream>
#include<string>
using namespace std;
#include<lua.hpp>
#include<luabind/function.hpp>
void testFunc()
{
cout<<"helo there, i am a cpp fun"<<endl;
}
int main(int argc, char* argv[])
{
//首先声明luaState环境
using namespace luabind;
lua_State* L = lua_open();    //也可以用luaL_newState()函数
luaL_openlibs(L);    //注意将lua默认库打开,要不会出现N多错误的,比如print函数都没有
//将c++中的函数暴露给lua
module(L, "cppapi")
[
def("testFunc", (void(*)(void))testFunc)
];
//加载lua脚本,我们临时起名test.lua
luaL_dofile(L, "test.lua");
try
{
//调用lua中的整形全局变量
int nLuaGlobal = luabind::object_cast<int>(luabind::globals(L)["nGlobal"]) ;
//调用lua中的字符串变量
string strLuaGlobal = luabind::object_cast<string>(luabind::globals(L)["strGlobal"]);
//获取table,方法一,通过luabind::object 固有方法
luabind::object luaTable = luabind::globals(L)["t"] ;
string name=luabind::object_cast<string>(luaTable["name"]) ;
int age = luabind::object_cast<int>(luaTable["age"]) ;
//获取table,方法二,通过gettable
string desc = luabind::object_cast<string>(luabind::gettable(luaTable,"desc"));
//下面是调用lua中函数
int nAddRes = luabind::call_function<int>(L, "add", 3, 4) ;
string strEchoRes = luabind::call_function<string>(L, "strEcho", "c++参数") ;
}
catch(...)
{
cout<<"error"<<endl;
}
return 0;
}

 

转载于:https://www.cnblogs.com/tt-tt/archive/2012/11/01/2749972.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值