gpt4 book ai didi

c++ - C++ 和 lua 的通用类型

转载 作者:行者123 更新时间:2023-11-28 06:33:03 25 4
gpt4 key购买 nike

我有一个包含一些属性(数据片段)的 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 绑定(bind)库)实现这一点? luabind::object 类看起来很有前途,但它在其构造函数中使用了一个 lua_State 指针。这让我很担心,因为我觉得 Entity 类真的不应该知道任何关于 Lua 状态的信息。

最佳答案

在 LuaBind 中,您的实体类不需要知道任何关于 lua 状态的信息。 Lua 绑定(bind)不必在语法上与 C++ API 一对一相同,因为它们是完全不同的语言。

在您的情况下,我宁愿将 api 拆分为 getter 和 setter。使用显示的 Entity 类,您可能会努力让 LuaBind 明确地执行您想要执行的操作。您可以做的是在 C++ 端为 Entity 编写一个包装类,它将具有符合 LuaBind 的简单接口(interface),即使用明确的名称拆分 getter 和 setter。

Blufs是一个例子,说明了我的意思。

作为一个简单的例子,with LuaBridge :

创建一个简单的非手卷绑定(bind)有点棘手:

class Entity {
std::map<std::string, int> attributes;

public:
void attribute(std::string const& key,int value) {
attributes[key] = value;
}

int& attribute(std::string const& key) {
return attributes[key];
}
};

可以改为绑定(bind)一个包装器:

class EntityWrapper {
Entity entity;
public:
void set_int(std::string const& key,int value) {
entity.attribute(key,value);
}


int get_int(std::string const& key) {
return entity.attribute(key);
}
};

一个简单的绑定(bind):

void luabridge_bind(lua_State *L) {
luabridge::getGlobalNamespace(L)
.beginClass<EntityWrapper>("Entity")
.addConstructor<void(*)(), RefCountedPtr<EntityWrapper> /* creation policy */ >()
.addFunction("get_int", &EntityWrapper::get_int)
.addFunction("set_int", &EntityWrapper::set_int)
.endClass()
;
}

在 Lua 中:

local e = Entity()
e:set_int("bla",42)
print(e:get_int("bla"))

如果您需要实体与其他 API 进行交互,请编写小型包装器以获取原始包装对象并将其传递给其他函数。

关于c++ - C++ 和 lua 的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com