EDIT: corrected typos mentioned below - thanks for the hint.
To clarify, as it may be confusing in the begining, Nasal knows two different (but somehow similar) composite data types: vector and hash. They are similar in that they store an arbitrary number of elements (which can be either primitive like numbers, booleans, strings or again a vector or hash.
The difference lies in the way the elements are "addressed": a vector (similar to "array" in other languages) automatically numbers the elements from 0 to n-1
Vectors are created using squared bracket and you can only access elements by an integer (index) like this
- Code: Select all
var myvector = ["foo", "bar", 42, ];
print(myvector[0]);
A hash on the other hand is not limited to integers as keys, you can also use strings as a key. A hash is defined using { }
- Code: Select all
var myhash = {
"foo": "bar",
foo2: "key without quotes is ok",
42: "the answer",
};
print(myhash[42]);
Now, you can use
- Code: Select all
forindex (var idx; myvector) { print(idx, ": ", myvector[idx]); }
only on vectors while you can use
- Code: Select all
foreach (var key; myhash) { print(key, ": ", myhash[key]); }
on hashes and also on vectors - for a vector the keys will be the integer indices.
Only for hashes you can use the keys(myhash) function which returns a vector containing all keys of a hash
Last but not least you can use
- Code: Select all
if (typeof(foo) == "hash" or typeof(foo) =="vector") { do_stuff(); }
if you plan some vector in hash or hash in vector thing.