hush-shell / hush

Hush is a unix shell based on the Lua programming language
MIT License
658 stars 23 forks source link

Confusion about indexing behavior #49

Open bsdelf opened 2 months ago

bsdelf commented 2 months ago

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 commented 2 months ago

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
>