Error invalid access of index 4 on array

A little help guys
This may be dumb but i really can’t figure this out

so have a look at this script

func solve():
while currentoperation != totalblocks:
currentoperation = currentoperation + 2
if mainequation[currentoperation] == “+”:
add(float(currentlysolved), float(mainequation[currentoperation + 1]))
elif mainequation[currentoperation] == “-”:
subtract(float(currentlysolved), float(mainequation[currentoperation + 1]))
elif mainequation[currentoperation] == “*”:
multiply(float(currentlysolved), float(mainequation[currentoperation + 1]))
elif mainequation[currentoperation] == “/”:
Divide(float(currentlysolved), float(mainequation[currentoperation + 1]))
else:
print(“no operations found”)

answerdisplay.text = str(currentlysolved)

i get the error invalid access of index 4 on array

For context, currentoperation and total blocks are integers, main equation is a array
what i’m trying to do is get the value stored in mainequation array using current operation.

Also i don’t know how to convert this text to script so maybe a little help with that

Thanks :slight_smile:

If your array contains 4 elements you can’t reach to index 4, because indexers start from 0, so the fourth element will be index 3, you need to end your while loop before:

while currentoperation < mainequation.size():

Also when posting on forum, use the </> button in the text editor to format your code, its hard to read as is, also i recommend using _ to separare the words from your variables, makes easier to read.

So the array ends 1 digit early right? So since my equation was 5+5: and it counted as 3 terms as it started from 0. Got it! And about that variable u mean Variable_Name right? Yea I’m out of practice of that I’ll fix that. Thanks for your answer

Yes, always starting from 0 and ending in Array.size() - 1. Also, if you doing a calculator using a string input you can use Expression instead.

I was making it with string right I’ll go through the expression docs, clean code goes a long way

I’m a bit late for this but I just wanted to thank you, the expression class helped alot, I made the calculator in just 10 mins (probably even lesser)

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.