游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2280|回复: 0

通过 LuaBind 让 C++函数返回Lua表

[复制链接]

1

主题

2

帖子

6

积分

新手上路

Rank: 1

积分
6
发表于 2010-6-12 15:57:00 | 显示全部楼层 |阅读模式
可以去我的博客看看,格式比较好:
http://blog.csdn.net/jadedrip/archive/2010/06/12/5665828.aspx

由于要返回表,我们的C++函数需要返回 luabind:bject 对象。另外,参数里需要定义一个 lua_State * 指针。

C++ 函数可以这么定义:

view plaincopy to clipboardprint?
luabind::object myfunc(   
    const std::string & param,     // 参数  
    lua_State* lstate );  


用 luabind 绑定函数时,需要指定绑定策略为 raw:

view plaincopy to clipboardprint?
luabind::module(g_luaState) [  
    luabind::def( "myfunc", &myfunc, luabind::raw(_2) )  
];  


raw 后面的参数指示  lua_State * 是C++函数里的第几个参数,我们的例子里是第二个,所以使用 _2.

最后,我们要在C++函数里准备一个表用来返回:

view plaincopy to clipboardprint?
luabind::object myfunc(   
    const std::string & param,     // 参数  
    lua_State* lstate )  
{  
    ...  
    luabind::object result=newtable( lstate );  
    int idx=1; // lua 里的数组从1开始  
    ...  
    result[idx++]=1;  
    ...  
    return result;  
}  


另外,result 也可以传入其他主键,比如 result["mytext"]="Hello";

在 lua 脚本里看看结果吧:

view plaincopy to clipboardprint?
local env=myfunc( "Hello lua" )  
table.foreach( env,  function(i, v) print (i, v) end )  http://blog.csdn.net/jadedrip/archive/2010/06/12/5665828.aspx
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-6-8 15:38

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表