您需要某种反射才能动态获取索引 i 处的成员。
不幸的是,标准 c++ 中没有任何东西可以为您做到这一点。
有几种方法可以让它发挥作用:
- 最简单的解决方案是只读取值并将它们直接分配给敌人对象,例如:
Enemy e;
lua_pushnumber(L, 1);
lua_gettable(L, -2);
e.name = lua_tostring(L, -1);
// ...
但是,如果您有很多成员,这将很快变得非常混乱。
- 假设您可以对所有成员(例如所有字符串)使用相同的类型,您可以使用向量而不是
Enemy 结构,例如:
std::vector<std::string> enemy;
for(int i = 0; i < length; i++) {
lua_pushnumber(L, i);
lua_gettable(L, -2);
enemy.push_back(lua_tostring(state, -1));
lua_pop(L, 1);
}
此解决方案的明显缺点是您需要在向量中使用索引,而不是像 health、name 等花哨的名称。而且您仅限于单一类型。
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/algorithm/iteration.hpp>
#include <lua/lua.hpp>
struct Enemy
{
std::string name;
int health;
int family;
int level;
} enemy;
BOOST_FUSION_ADAPT_STRUCT(
Enemy,
(std::string, name)
(int, health)
(int, family)
(int, level)
)
struct LuaVisitor {
LuaVisitor(lua_State* state) : idx(1), state(state) {}
void operator()(std::string& strVal) const {
next();
// TODO: check if top of stack is actually a string (might be nil if key doesn't exist in table)
strVal = lua_tostring(state, -1);
lua_pop(state, 1);
}
void operator()(int& intVal) const {
next();
// TODO: check if top of stack is actually a number (might be nil if key doesn't exist in table)
intVal = lua_tonumber(state, -1);
lua_pop(state, 1);
}
void next() const {
lua_pushnumber(state, idx++);
lua_gettable(state, -2);
}
mutable int idx;
lua_State* state;
};
int main(int argc, char* argv[]) {
// create a sample table
lua_State* state = luaL_newstate();
luaL_dostring(state, "return {\"Hello World\", 1337, 12, 123}");
// read the enemy from the table
Enemy e;
boost::fusion::for_each(e, LuaVisitor(state));
std::cout << "[Enemy] Name: " << e.name << ", health: " << e.health << ", family: " << e.family << ", level: " << e.level << std::endl;
lua_close(state);
return 0;
}
这将使您能够动态设置Enemy 结构的成员,但是boost 非常重,您需要使BOOST_FUSION_ADAPT_STRUCT 宏与实际结构保持同步。
- 您还可以使用 lua 绑定库,例如
luaaa 将您的 Enemy 对象直接映射到 lua(而不是传递一个表格):
#include <lua/luaaa.h>
struct Enemy
{
Enemy() {}
virtual ~Enemy() {}
void init(std::string _name, int _health, int _family, int _level) {
name = _name;
health = _health;
family = _family;
level = _level;
}
std::string name;
int health;
int family;
int level;
};
void myFunction(Enemy* e) {
std::cout << "[Enemy] Name: " << e->name << ", health: " << e->health << ", family: " << e->family << ", level: " << e->level << std::endl;
}
int main(int argc, char* argv[]) {
// init lua & bindings
lua_State* state = luaL_newstate();
luaaa::LuaClass<Enemy> luaEnemy(state, "Enemy");
luaEnemy
.ctor()
.fun("init", &Enemy::init);
luaaa::LuaModule mod(state, "sampleModule");
mod.fun("myFunction", myFunction);
luaL_dostring(state, R"(
enemy = Enemy.new()
enemy:init("My Enemy", 1, 2, 3)
sampleModule.myFunction(enemy)
)");
lua_close(state);
return 0;
}
那么就可以直接使用lua中的敌人对象了:
enemy = Enemy.new()
enemy:init("My Enemy", 1, 2, 3)
sampleModule.myFunction(enemy)
希望这些选项之一涵盖您的用例;)