Index access allows you to retrieve and modify elements in arrays, lists, strings, and object properties using square bracket notation []. This is fundamental for working with collections and data structures in Soul.
text = "Hello"// Read charactersfirst = text[0] // "H"second = text[1] // "e"last = text[4] // "o"// Note: String modification may not be supported// text[0] = "h" // May not work - strings might be immutable
items = ["apple", "banana", "cherry"]// Traditional for loop with indexfor (i = 0; i < items.length(); i++) { println("Index " + i + ": " + items[i])}// For-in loop with index (if supported)for (index, item in items) { println("Index " + index + ": " + item)}
Use meaningful names: users[currentIndex] instead of users[i]
Handle errors: Wrap index access in try-catch when needed
Cache lengths: Store array lengths in variables for performance
Use safe access: Create helper functions for safe index operations
Copy
Ask AI
// Good - safe index accesssoul getUserById(users, userId) { for (i = 0; i < users.length(); i++) { if (users[i]["id"] == userId) { return users[i] } } return null}// Better - with validationsoul getUserById(users, userId) { if (users == null || users.length() == 0) { return null } for (i = 0; i < users.length(); i++) { user = users[i] if (user != null && user["id"] == userId) { return user } } return null}
Index access is fundamental to working with data structures in Soul. Use it carefully with proper bounds checking and error handling to create robust applications.