Associative Arrays
An Associative Array (sometimes also called a Map or a Dictionary) is like a normal Array in the way that it is able to store multiple entries. Unlike Arrays however, you can choose what type you want the index, or (as we call it in maps) key, to be!
Declaring an Associative Array
You declare Associative Arrays using curly brackets {}
and colons :
Let’s break this down, shall we?
val myAssocArray =
standard variable declaration{
this is an Associative Array, Sir!dirt : <minecraft:dirt>
we map<minecraft:dirt>
under the stringdirt
,
wait, there’s more to comegold : <minecraft:gold_ingot>
we map<minecraft:gold_ingot>
under the stringgold
}
we have reached the end of the Array, Sir!as IItemStack[string];
this is an Associative Array that uses strings as indices and IItemStacks as values.
Okay, so what do I need to think of when using these?
- You can use about every type available to Zenscript as either key or value.
- You cannot use variables for key declaration in the initial Declaration (the one that uses
{}
) as clear Text is interpreted as string!
Refering to Items inside an Associative Array.
You refer to items inside an Associative Array the same way you refer to items inside a normal Array:
Array[index]
Only difference is this time, you don’t necessarily need to use an Integer as index, but whatever type you declared your Array to be!
There is one special case, that is when you use strings as indeces:
In this case you can also use the memberGetter like this:
Manipulating items inside an Associative Array
As in Arrays, you can manipulate items inside an Associative Array using array[index] = newValue
.
There is one major differenc though:
While Arrays have a fixed size, maps don’t. That means you can always add an entry by setting to an index that has previously not been set!
Retrieving an Associative Array’s Key and Entrysets
The KeySet is an array containing all the map’s keys.
The valueSet is an array containing all the map’s values.
The entrySet is an array containing all the map’s entries (see below).
Iterating over an Associative Array
There are two Iterators that allow you to iterate over an Associative Array:
- The key-Iterator: Iterates over the keys, uses one variable
- The key-value-Iterator: Iterates over the keys and values, uses two variables
Let’s add an Associative Array that stores crafting recipes to be iterated over:
- Keys shall be the crafting output as IItemStack
- Values shall be the crafting ingredients as IIngredient
- We shall use the key-Iterator that is built like this:
for key in assocArray {doSth;}
- We shall also use the key-value-Iterator that is built like this
for key, value in assocArray {doSth;}
ZenType Entry
A map Entry consists of a key and a value.
Currently the only way to get such an object is via a map’s entrySet method.
You can use the getters to get key
and value