c++ - 如何使用 LuaBind 将 std::map 绑定(bind)到 Lua

标签 c++ stl lua luabind

我正在尝试公开我的 std::map<std::string, std::string>作为 Lua 的类属性。我已经为我的 getter 和 setter 设置了这个方法:

luabind::object FakeScript::GetSetProperties()
{
    luabind::object table = luabind::newtable(L);
    luabind::object metatable = luabind::newtable(L);

    metatable["__index"] = &this->GetMeta;
    metatable["__newindex"] = &this->SetMeta;

    luabind::setmetatable<luabind::object, luabind::object>(table, metatable);

    return table;
}

这样我就可以在 Lua 中做这样的事情了:

player.scripts["movement"].properties["stat"] = "idle"
print(player.scripts["movement"].properties["stat"])

但是,我在 C++ 中提供的代码没有得到编译。它告诉我在这一行 metatable["__index"] = &this->GetMeta; 有一个对重载函数的模糊调用和它后面的那一行。我不确定我这样做是否正确。

错误信息:

error C2668: 'luabind::detail::check_const_pointer' : 
ambiguous call to overloaded function
c:\libraries\luabind-0.9.1\references\luabind\include\luabind\detail\instance_holder.hpp    75

这些是 SetMetaGetMetaFakeScript :

static void GetMeta();
static void SetMeta();

以前我为 getter 方法这样做:

luabind::object FakeScript::getProp()
{
    luabind::object obj = luabind::newtable(L);

    for(auto i = this->properties.begin(); i != this->properties.end(); i++)
    {
        obj[i->first] = i->second;
    }

    return obj;
}

这很好用,但它不允许我使用 setter 方法。例如:

player.scripts["movement"].properties["stat"] = "idle"
print(player.scripts["movement"].properties["stat"])

在这段代码中,它只是在两行中触发 getter 方法。虽然如果它让我使用 setter,我将无法从属性中获取 key ["stat"]就在这里。

这里有 LuaBind 方面的专家吗?我见过大多数人说他们以前从未使用过它。

最佳答案

您需要使用(未记录的)make_function() 从函数创建对象。

metatable["__index"] = luabind::make_function(L, &this->GetMeta);
metatable["__newindex"] = luabind::make_function(L, &this->GetMeta);

不幸的是,这个(最简单的)make_function 重载被破坏了,但你只需要 insert f作为 make_function.hpp 中的第二个参数。

关于c++ - 如何使用 LuaBind 将 std::map 绑定(bind)到 Lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578469/

相关文章:

c - lua_newthread() & LUA_REGISTRYINDEX 独立

c++ - 图像处理 - 两张图像之间的差异

c++ - 试图从输入文件中获取字符

c++ - Std::vector 被初始化为垃圾。奇怪的行为。有什么想法吗?

c++ - 不能对 std::set<std::string, std::less<>> 使用用户提供的比较函数

c++ - std:sort 与插入 std::set

lua - 使用 ClassNLCriterion 在 Torch 中进行批处理

c++ - 为什么 std::declval<int>() = std::declval<int>() 无效?

c++ - 关于 GetProcAddress

lua - 为什么同一个lua脚本执行结果不一致?