У Lua есть что-то под названием Tables, которое позволяет вам добавлять пары ключ-значение без предопределенного struct
, как в C/C++. Таким образом, код Lua вы вывесили добавляет пар ключ-значение pool
(читать комментарии в коде):
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
определение сверху в .h файле ниже выше class Kingdom
):
// 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 использует таблицы, поэтому вы можете создать эквивалент в C++ с помощью std::map<>. Тогда вы могли бы использовать 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<>
вам придется запоминать строки, которые не являются хорошей практикой, и ваша среда разработки должна иметь intellisense, которая всегда будет показывать вам содержимое struct Pool
всякий раз, когда вы нажимаете на операторы .
или ->
,
well isnt pool a struct here? просто объявите структуру и создайте функцию конструктора и инициализируйте эту структуру и верните ее указатель. Обязательно укажите структуру внутри конструктора, иначе она будет только локальной для области видимости функции, а ее адрес - отвратительный указатель ur. – xetra11