dictu-lang / Dictu

Dictu is a high-level dynamically typed, multi-paradigm, interpreted programming language.
https://dictu-lang.com
MIT License
267 stars 53 forks source link

[FEATURE] list methods should support negative index #740

Closed haifenghuang closed 2 months ago

haifenghuang commented 6 months ago

Is there an existing issue for this?

Is your feature request related to a problem?

Since the list support negative index, so In lists.c file, insertListItem and popListItem should also support negative index. Take insertListItem as an example:

    int index = AS_NUMBER(args[2]);

    if (index < 0 || index > list->values.count) {
        runtimeError(vm, "Index passed to insert() is out of bounds for the list given");
        return EMPTY_VAL;
    }

Describe the solution you'd like

It should be like below:

    int index = AS_NUMBER(args[2]);
    if (index < 0) index = list->values.count + index; // allow negative indexes   
    if (index < 0 || index > list->values.count) {
        runtimeError(vm, "Index passed to insert() is out of bounds for the list given");
        return EMPTY_VAL;
    }

Describe alternatives you've considered

No response

Additional context

No response

Jason2605 commented 6 months ago

Valid comment, happy for you to PR this mate!