Adding a sequence of inputted values

Godot Version

Godot 4

Question

Hi there! I’m currently working on a till system that in theory, would be able to add up a number of values that you input via an on-screen keypad.

The numbers you input would come up on the bottom and screen and would transfer to the top once added - I’m essentially using “Ent” as the + symbol and “Total” as the =

I’ve been able to add two numbers together via the following code:

func _on_ent_btn_pressed():
has_been_used = false
first_number = bottom_display.text.to_float()
top_display.text = str(first_number)

func _on_total_btn_pressed():
has_been_used = false
new_number = bottom_display.text.to_float()
result = first_number + new_number
top_display.text = str(result)

The trouble comes with adding another, or several, more numbers to the result. I know that using “first_number” and “second_number” limits me to be able to use more, but as the player would be putting any number of items through the till, I need a way for that to work.

Any help would be greatly appreciated, I am still quite new and could use all the advice I can get! Thank you!

You’d want to use an Array (Array — Godot Engine (stable) documentation in English) to do this if I’m understanding your goal correctly - storing all the numbers together and then adding them all up in a loop.

for instance, something like:

number_array.append(new_number)

followed later by…

var sum = 0.0
for number in number_array:
    sum += number
1 Like

just add a running total for your ent_btn_pressed

you can break it out into two readable steps or just add += to your text to float conversion

 var temp_number = bottom_display.text.to_float()
 first_number = first_number + temp_number
# or
 first_number += bottom_display.text.to_float()

These are the same thing.

just remember to zero out first_number after total is pressed and before you start.

1 Like

That’s worked perfectly, thank you!! Couldn’t get my head around making a temporary value but it makes sense now

I’ve got it working thanks to pennyloafers but that does make arrays make more sense, thank you!

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