Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Confusion about indexing behavior #49

Open
bsdelf opened this issue Sep 4, 2024 · 1 comment
Open

Confusion about indexing behavior #49

bsdelf opened this issue Sep 4, 2024 · 1 comment

Comments

@bsdelf
Copy link

bsdelf commented Sep 4, 2024

The document says accessing an index out of bound result in panic

Indexing [], .: array, dict, string, error only. Attempts to access an index out of bounds will result in a panic. Additionally, dicts and errors may be indexed with the dot . operator, as long as the key is a valid identifier.

So I understand following two cases will fail

# case 1
let arr = []
std.print(arr[0]) # panic, index (0) out of bounds
# case 2
let dict = @[]
std.print(dict["a"]) # panic, index ("a") out of bounds

However, if I put the indexing operator on the left hand side, the behavior seems to be inconsistent

# case 3
let arr = []
arr[0] = 1 # panic, index (0) out of bounds
std.print(arr[0])
# case 4
let dict = @[]
dict["a"] = 1 # no panic here, a new key-value pair is inserted
std.print(dict["a"])

It feels like case 4 does not follow the documentation.

@caioraposo
Copy link
Contributor

I think we should update the documentation, as dict["a"] on the left-hand side means insertion (for dicts at least). The current behavior is consistent with other languages such as Python and Lua:
(Python)

>>> d = {}
>>> d["a"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> d["a"] = 1
>>>

(Lua; doesn't panic on case 2 but case 4 works as expected)

> d = {}
> d["a"]
nil
> d["a"] = 1
>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants