dictu-lang / Dictu

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

[FEATURE] list methods should support negative index #740

Open haifenghuang opened 3 months ago

haifenghuang commented 3 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 3 months ago

Valid comment, happy for you to PR this mate!