【发布时间】:2014-11-29 21:52:28
【问题描述】:
我有一个Entity 类,其中包含一些属性(数据片段)。这些属性存储在 name => value 的映射中。
class Entity
{
public:
// Sets the attribute with the specified name.
void attribute(const std::string& name, const GenericType& value) {
m_attributes[name] = value;
}
// Returns the attribute with the specified name.
GenericType& attribute(const std::string& name) {
return m_attributes[name];
}
template<typename AttributeType>
void attribute(const std::string& name, const AttributeType& value) {
m_attributes[name] = GenericType(value);
}
template<typename AttributeType>
AttributeType& attribute(const std::string& name) {
return generic_cast<AttributeType>(m_attributes[name]);
}
private:
// Map of attributes from name => value.
std::unordered_map<std::string, GenericType> m_attributes;
}
我有一个创建或覆盖属性的方法和另一个返回具有指定名称的属性的方法。前两种方法暴露给 Lua。最后两种方法用于访问和修改我的 c++ 源代码中的属性。问题是属性可以是任何类型。例如,我希望能够做到:
entity.attribute("Health", 100)
entity.attribute("Position", Vector3(1,2,3))
entity.attribute("Position").x = 4
应该可以从我的 c++ 源文件和 lua 脚本中读取和修改属性。我以前一直在使用 ChaiScript,我使用 Boxed_Value 类作为我的 GenericType。这工作得很好,但过多的编译时间迫使我寻找其他地方。
有没有办法通过 LuaBind(或任何其他 Lua 绑定库)实现这一点? luabind::object 类看起来很有希望,但它的构造函数中需要一个 lua_State 指针。这让我很担心,因为我觉得 Entity 类真的不应该知道关于 Lua 状态的任何事情。
【问题讨论】:
-
如果您请求支持 ChaiScript 编译时间会很有帮助,有一些技术可以减少它。
-
@lefticus 我能够减少编译时间,我仍然在使用 ChaiScript,因为我真的很喜欢这种语言。由于我使用 ChaiScript 获得的编译时间,这个问题并没有真正提出。我还对其他语言绑定库如何处理泛型类型感兴趣。
-
很好,感谢更新。