user2566343
user2566343

Reputation: 35

Iterate in YAML

I have the following YAML:

Configuracion:
  vel_personaje: 3
  merge_scroll: 30


Tipos:
    nombre: arbol
    imagen: img/tree
    ancho_base: 2
    alto_base: 2
    pixel_ref_x: 30
    pixel_ref_y: 40
    fps: 10
    delay: 5

    nombre: casa
    imagen: img/house

    nombre: auto
    imagen: img/tree
    ancho_base: 2
    alto_base: 2

The thing is that i can have as many "Tipos" as I want, but sometimes they have 8 parameters, sometimes just 2, or any number in between those two. I'm trying to figure out how to read those values with yaml-cpp, but I'm not being able to do it. I tried the following, but with no luck.

while (contador < tipos_size){

    try {
        name = tipos["nombre"].as<string>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        name = "pepe";
    }

    try {
        imagen = tipos["imagen"].as<string>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        imagen = "img/def";
    }

    try {
        ancho_base = tipos["ancho_base"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        ancho_base = 1;
    }

    try {
        alto_base = tipos["alto_base"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        alto_base = 1;
    }

    try {
        pixel_ref_x = tipos["pixel_ref_x"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        pixel_ref_x = 10;
    }

    try {
        pixel_ref_y = tipos["pixel_ref_y"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        pixel_ref_y = 10;
    }

    try {
        fps = tipos["fps"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        fps = 24;
    }

    try {
        delay = tipos["delay"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        delay = 100;
    }

I will appreciate any help. Thanks!

EDIT CODE:

    for (YAML::Node tipo : tipos) {

    try {
        name = tipo["nombre"].as<string>();
    } catch (YAML::Exception& yamlException) {
        name = "pepe";
    }

Upvotes: 2

Views: 2264

Answers (1)

Jesse Beder
Jesse Beder

Reputation: 34054

It looks like you want Tipos to be a sequence of maps, not a map:

Configuracion:
  vel_personaje: 3
  merge_scroll: 30


Tipos:

  - nombre: arbol
    imagen: img/tree
    ancho_base: 2
    alto_base: 2
    pixel_ref_x: 30
    pixel_ref_y: 40
    fps: 10
    delay: 5

  - nombre: casa
    imagen: img/house

  - nombre: auto
    imagen: img/tree
    ancho_base: 2
    alto_base: 2

The, you can iterate like:

for (YAML::Node tipo : tipos) {
  // handle tipo
}

Upvotes: 1

Related Questions