C++ 在Selene中包装一个枚举,以便在Lua中访问
我用来包装C++类和函数,以便从Lua访问。我有一个简单的枚举类:C++ 在Selene中包装一个枚举,以便在Lua中访问,c++,enums,lua,C++,Enums,Lua,我用来包装C++类和函数,以便从Lua访问。我有一个简单的枚举类: enum class Motion { UP = 0, DOWN = 1, REPEAT = 2, }; 我想把它包装在一个Lua状态中,这样我就可以在Lua中说“Motion.DOWN”这样的话,得到1 第一次尝试: void register(sel::State &L) { L["Motion"].SetClass<Motion>(); } 第二次尝试: void r
enum class Motion {
UP = 0,
DOWN = 1,
REPEAT = 2,
};
我想把它包装在一个Lua状态中,这样我就可以在Lua中说“Motion.DOWN”这样的话,得到1
第一次尝试:
void register(sel::State &L) {
L["Motion"].SetClass<Motion>();
}
第二次尝试:
void register(sel::State &L) {
L["Motion"] = Motion;
}
这不编译,得到关于“预期主表达式”的错误,它不是有效的C++。如果我尝试使用
&Motion
,我会收到相同的错误
有办法做到这一点吗?最好不要让我再次列出所有枚举常量。这在Selene中是不可能的 我采用的解决方案是定义一个类
DynEnum
,它在内部使用一个映射来跟踪标签和值
/**
* Simple class for enum values
*/
class DynEnum {
public:
DynEnum(std::map<std::string, int> tbl) : tbl(tbl) {}
int of(std::string tag) {
if (tbl.count(tag) > 0) {
return tbl[tag];
}
throw std::runtime_error("Enum tag not found");
}
std::string lookup(int v) {
for (auto &p : tbl) {
if (p.second == v) {
return p.first;
}
}
throw std::runtime_error("Enum value not found");
}
private:
std::map<std::string, int> tbl;
};
然后使用Selene绑定:
L["Motion"].SetObj(Motion,
"of", &DynEnum::of,
"lookup", &DynEnum::lookup);
这种方法有性能开销,但在我的应用程序中这不是什么大问题。它还具有允许在Lua中从数字转换为字符串的优点,这有助于调试。这在Selene中是不可能的 我采用的解决方案是定义一个类
DynEnum
,它在内部使用一个映射来跟踪标签和值
/**
* Simple class for enum values
*/
class DynEnum {
public:
DynEnum(std::map<std::string, int> tbl) : tbl(tbl) {}
int of(std::string tag) {
if (tbl.count(tag) > 0) {
return tbl[tag];
}
throw std::runtime_error("Enum tag not found");
}
std::string lookup(int v) {
for (auto &p : tbl) {
if (p.second == v) {
return p.first;
}
}
throw std::runtime_error("Enum value not found");
}
private:
std::map<std::string, int> tbl;
};
然后使用Selene绑定:
L["Motion"].SetObj(Motion,
"of", &DynEnum::of,
"lookup", &DynEnum::lookup);
这种方法有性能开销,但在我的应用程序中这不是什么大问题。它还具有允许在Lua中从数字转换为字符串的优点,这有助于调试