Lists ([1, 2, 3])
Luma supports lists as a core data structure, offering both mutability and simplicity, along with a rich set of methods inspired by modern programming languages.
Declaration
nums: [int] = [1, 2, 3]
words: [str] = ["hello", "world"]Access & Walk
Index Access
print(nums[0]) // prints: 1Safe Access
val: ?int = nums.get(0) // returns 1
val = nums.get(10) // returns nilSafe Access
val: ?int = nums.get(0) // returns 1
val = nums.get(10) // returns nilWalk a List
nums.walk(index, value) -> {
print("${index}: ${value}")
}
nums.walk(value) -> print(value)Core Methods
| Operation | Syntax | Returns |
|---|---|---|
| Get Length | nums.len() | Number of elements |
| Get by Index | nums.get(1) / nums[1] | Optional value (?T) |
| Find Index of Value | nums.index_of(3) | Optional index (?int) |
| Add Value | nums.add(4) | Mutates the list |
| Remove by Value | nums.remove(2) | Returns true or false |
| Remove by Index | nums.remove_at(1) | Removes element at index |
| Intersect | nums.intersect([1, 3]) | New list with common values |
Immutable Alternatives
For functional-style workflows:
| Operation | Syntax | Returns |
|---|---|---|
| Add | nums + [4] | New list |
| Remove | nums - [2] | New list |
Advanced Features
| Feature | Syntax / Method | Returns |
|---|---|---|
| Slicing | nums[0…2] | [1, 2, 3] |
| Bulk Add | nums.add_all([4, 5]) | Mutates list |
| Bulk Remove | nums.remove_all([1, 2]) | Mutates list |
| Sort | nums.sort() | Sorts in place |
| Filter | nums.filter(x -> x > 1) | New filtered list |
Design Principles
- Intuitive Syntax: Square brackets, slicing, and dot methods are easy to learn.
- Safe by Default:
.get()and.index_of()returnnilinstead of crashing. - Consistent: All methods use snake_case.
- Mutable + Immutable: Choose your preferred style.
- Performant: Mutations are optimized internally.
Equality
[1, 2] == [1, 2]→true[1, 2] == [2, 1]→false(order matters)- Sort before comparing if needed:
sorted1 = list1.sort()
sorted2 = list2.sort()
print(sorted1 == sorted2)Examples
nums: [int] = [1, 2]
nums.add(3) // [1, 2, 3]
nums.remove(2) // true
found: ?int = nums.get(1) // 3
// Immutable style
new_nums = nums + [4] // [1, 3, 4]
filtered = new_nums.filter(x -> x > 1) // [3, 4]
// Advanced
slice = nums[0..1] // [1]
nums.sort() // [1, 3]
common = nums.intersect([3]) // [3]Edge Cases
| Case | Behavior |
|---|---|
| .get(99) | Returns nil |
| .index_of(“xyz”) | Returns nil |
| .remove(“x”) | Returns false |
| .intersect([]) | Returns empty list |
Last updated on