金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
传Lua对象到Cpp

(金庆的专栏)

摘自:http://raycast.net/lua-intf

以下代码演示了Lua函数和表传入Cpp进行处理:

std::string acceptStuff(LuaRef luaObj,
    const std::vector<std::string>& stringVector,
    std::map<std::string, int>& dict)
{
    // Assume that this function expects Lua object (table) as first argument
    auto func = luaObj.get<std::function<std::string(int)>>("func");
    auto stringField = luaObj.get<std::string>("str");
    std::ostringstream s;
    s << "func() result: " << func(10) << ", string field value: " << stringField << "\n";
    s << "Vector size: " << stringVector.size() << ", first element: " << stringVector[0] << "\n";
    s << "Dictionary size: " << dict.size() << ", first element: (" <<
        dict.begin()->first << ", " << dict.begin()->second << ")";
    return s.str();
}

LuaBinding(lua).beginModule("test")
    .addFunction("acceptStuff", &acceptStuff)
.endModule();

// Lua
local obj = {
    func = function(i)
        return "You passed number " .. i
    end,
    str = "Hello, world"
}
local v = { 1, 2, 3 }
local dict = { first = 1, second = 2 }
print(test.acceptStuff(obj, v, dict))

// Output
func() result: You passed number 10, string field value: Hello, world
Vector size: 3, first element: 1
Dictionary size: 2, first element: (first, 1)
posted on 2016-07-19 16:09 金庆 阅读(398) 评论(0)  编辑 收藏 引用 所属分类: 1. C/C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理