我正在尝试公开我的 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
这些是 SetMeta
和 GetMeta
在FakeScript
:
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/