Nyx by Example

Maps

A Map stores key-value pairs with fast lookup by key. Maps are created with Map.new() and support insertion, retrieval, membership testing, and key enumeration.

Code

// Maps: Map.new(), insert, get, has, size, iterar con keys()

fn main() -> int {
    var capitales: Map = Map.new()

    // Insertar pares clave-valor
    capitales.insert("Argentina", "Buenos Aires")
    capitales.insert("Francia", "Paris")
    capitales.insert("Japon", "Tokio")

    // size
    print("paises: " + int_to_string(capitales.size()))

    // get
    let capital: String = capitales.get("Francia")
    print("Capital de Francia: " + capital)

    // has
    print("tiene Argentina: " + int_to_string(capitales.has("Argentina")))
    print("tiene Brasil: " + int_to_string(capitales.has("Brasil")))

    // Iterar claves
    let ks: Array = capitales.keys()
    print("claves (" + int_to_string(ks.length()) + "):")
    for k in ks {
        print("  " + k)
    }

    return 0
}

Output

paises: 3
Capital de Francia: Paris
tiene Argentina: 1
tiene Brasil: 0
claves (3):
  Argentina
  Francia
  Japon

Explanation

Maps in Nyx are created with Map.new() — there is no map literal syntax (it would be ambiguous with block expressions). Maps must be declared with var if you intend to insert or modify entries after creation.

The .insert(key, value) method adds or updates a key-value pair. .get(key) retrieves the value for a key, returning the stored value as a String (or the appropriate type). If the key does not exist, the behavior is undefined — use .has(key) first to check membership.

.has(key) returns an int: 1 means the key exists, 0 means it does not. This integer-as-boolean pattern is common in Nyx's low-level output functions. .size() returns the number of entries currently in the map.

.keys() returns an Array of all keys in the map. The iteration order over hash maps is not guaranteed to be insertion order, so key order in the output may differ between runs.

← Previous Next →

Source: examples/by-example/06-maps.nx