Lua 有一个叫做Tables 的东西,它允许你在没有预定义struct 的情况下添加键值对,就像在C/C++ 中一样。因此,您发布的 Lua 代码正在将键值对添加到 pool(在代码中读取 cmets):
local pool = {} -- Declare a new Table
pool.species = {} -- Add another Table to pool called 'species'
pool.generation = 0 -- Add the key 'generation' with value '0'
pool.innovation = Outputs -- Add the key 'innovation' with value 'Outputs'
pool.currentSpecies = 1 -- Add the key 'currentSpecies' with value '1'
pool.currentGenome = 1 -- Add the key 'currentGenome' with value '1'
pool.currentFrame = 0 -- Add the key 'currentFrame' with value '0'
pool.maxFitness = 0 -- Add the key 'maxFitness' with value '0'
在 C++ 中,您有多种选择。 1) 你可以创建一个struct 并声明你需要的东西(我猜是一些数据类型,但如果你有完整的 Lua 程序,你可以弄清楚它们):
struct Pool
{
Species species; // You'll have to define Species in another struct
int generation;
SomeEnum innovation; // You'll have to define SomeEnum in an enum
int currentSpecies;
int currentGenome;
int currentFrame;
int maxFitness;
}
如果你有一个类,那么你可以使用下面显示的struct Pool(将上面的struct Pool定义添加到class Kingdom上面的.h文件中):
// I'm doing this as a class since you are programming in C++ and I
// assume you will want to add more functions to operate on similar
// objects.
class Kingdom
{
public:
Kingdom();
Pool* NewPool();
private:
Pool _pool;
}
在您的 .cpp 文件中:
#include "Kingdom.h"
Kingdom::Kingdom()
{
// _pool.species = whatever you define struct Species as
_pool.generation = 0;
_pool.innovation = SomeEnum::Outputs; // You'll have to define SomeEnum
_pool.currentSpecies = 1;
_pool.currentGenome = 1;
_pool.currentFrame = 0;
_pool.maxFitness = 0;
}
Pool* Kingdom::NewPool()
{
Pool* newPool = new Pool;
memcpy(newPool, &_pool, sizeof(Pool)); // Make a copy
return newPool; // Return the new copy
// The newPool value is dynamic memory so when the calling function is done
// with newPool it should delete it, example:
// Kingdom myKingdom;
// Pool* myNewPoolStruct = myKingdom.NewPool();
// ... do some coding here
// delete myNewPoolStruct;
}
选项 2) 将是如果您的所有键值对都是同一类型;即所有键都是std::string,所有值都是int。请记住,Lua 代码使用表,因此您可以使用 std::map<> 在 C++ 中创建等效代码。然后你可以使用std::map<std::string, int>如下:
// In your .h file change
Pool* NewPool();
Pool _pool;
// to
std::map<std::string, int> NewPool();
std::map<std::string, int> _pool;
然后在您的 .cpp 文件中将构造函数更改为:
Kingdom::Kingdom()
{
_pool["species"] = 0; // Some int representation of species
_pool["generation"] = 0;
_pool["innovation"] = 1; // Some int representation of Outputs
_pool["currentSpecies"] = 1;
_pool["currentGenome"] = 1;
_pool["currentFrame"] = 0;
_pool["maxFitness"] = 0;
}
std::map<std::string, int> NewPool()
{
std::map<std::string, int> newPool;
newPool = _pool; // Copy - double check this against std::map
return newPool; // Double check this is a true copy and not a pointer
}
使用std::map,您可以像您提供的 Lua 代码一样即时创建键值对。简而言之,我会采用struct Pool 方法,因为使用std::map<>,您必须记住不是好的做法的字符串,并且您的IDE 应该具有智能感知,无论何时您都会向您显示struct Pool 的内容点击. 或-> 运算符。