np

list (type)

See also: list.lib

Description

Lists are one of the basic types of np, together with numbers, booleans, nil, and strings. Lists can contain two types of entries, ordered items (in an array-like fashion) and key-value pairs (like a hash map). A list can have either or both of these types of entries.

List Literals

A list can be created like this:

-- an empty list
new list1 = (:)
-- a list with ordered items
new list2 = (: 4 8 15 16 23 'and' 42)
-- a list with key-value pairs
new list3 = (: someKey = 'someValue' )
-- both:
new list4 = (: 2 3 5 7 11 someThing = 'blah' )

Using Lists

Accessing list members can be done by using the square bracket notation or, if referring to a simple alphanumerical key-value entry, with the dot notation:

new t = (: foo = 'bar' )
t[10] = 'baz'
print('foo is:' t.foo)
print('at position 10:' t[10])

-- list items are counted starting from 1
new t2 = ( 'a' 'b' 'c' )
print(t2[1])
a

Usage as an Array

If used as an array, lists are ordered arrays of items without explicit names. Their numbering comes from the order in which they are stored:

new l = (: 678 4237 33 'abc')

Array items can be iterated through with the items iterator:

l:each{ v | print(v) }
678
4237
33
abc

You can pop off entries of the array at arbitrary positions with the remove() behavior:

print('removed 1st item:' l:remove(1))
print('rest of l:' l)
removed 1st item:	678
rest of l:	(: 4237 33 "abc" )

And you can add() or mAdd() (=mutable add) items:

print(l:mAdd([[I'm new]]))
-- or, do it with an operator:
l += [[also, this]]
print(l)
(: 4237 33 "abc" "I'm new" )
(: 4237 33 "abc" "I'm new" "also, this" )

Usage as a Hash Table

Lists are also hash tables, when entries get assigned an explicit key. However, these key-value entries are not stored in a particular order:

new l = (: a='foo' b='bar' d='baz' )
print(l)
(: d="baz" a="foo" b="bar" )

To remove a key-value entry from a list, set its value to nil:

l.a = nil
print('l without a:' l)
l without a:	(: b="bar" d="baz" )

Similarly, you can add entries to the key-value store of a list by simply providing values for them:

l.c = [[new entry!]]
print(l)
(: c="new entry!" d="baz" b="bar" )

The Meaning of nil

If an entry is referred to but doesn't exist, nil is returned:

new t = (: foo = 'bar' )
print(t.baz)
nil

You can also set the value of a keyed entry to nil in order to erase it:

new t = (: foo = 'bar' )
print('t:' t) 
t.foo = nil
print('t:' t)
t:	(: foo="bar" )
t:	(: )

(Im)Mutability

Lists can be modified after they have been created. Some list operations are mutable, and some are immutable in the sense that a new list is returned after the operation. The mAdd() and mConcat() behaviors modify the list in place by adding a new entry or appending another list respectively - whereas their immutable counterparts add() and concat() leave the original list untouched.