Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to Add Variables in Sugarcube

edited July 2016 in Help! with 2.0
I am doing a small betting game where you have a balance. I made it so if you win, it would <<set $balance to $balance += $moneybet>> (I also did this as + instead of +=)
When I do this, it does not add the variables together, it adds them onto each other. (ex. If my balance was 10 and the money I bet was 5, instead of adding them to 15 it would make them 105)
Is there another macro, or am I doing the expressions wrong?
Please let me know.

Comments

  • edited July 2016
    Based on your result I am guessing that your original example looked something like the following:
    <<set $balance to "10">>
    <<set $moneybet to "5">>
    <<set $balance to $balance + $moneybet>>
    
    balance now equals String value "105"
    

    If that was the case then the issue is that you are assigning String values (a value delimited with quotes) to your variables instead of using Numerical values.
    <<set $balance to 10>>
    <<set $moneybet to 5>>
    <<set $balance to $balance + $moneybet>>
    
    balance now equals Numerical value 15
    

    note: If you want to use the += operator then the syntax would be:
    <<set $balance to 10>>
    <<set $moneybet to 5>>
    <<set $balance += $moneybet>>
    
    balance now equals Numerical value 15
    
  • can I do this with a textbox?
  • Your question is a little vague, I am assuming that you are asking how to allow the Reader to enter a value for the $moneybet variable using a <<textbox>> macro.

    There are a number of issues that need to be solved for this to work:

    1. A value (even one containing just numbers) entered into a <<textbox>> macro is a String, so you will need to convert that value to a number.

    2. The Reader may enter no value or one that contains letters or punctuation (excluding a decimal point) , neither of which can be converted into a number.

    The following uses a Javascript isNaN() function and a parseFloat() function to handle checking if the String value is a valid number and converting the String value to a Number, there are other validations that could also be done.
    <<set $balance to 10>>
    <<set $moneybet to 0>>
    
    Balance: <span id="balance">$balance</span>
    
    Money Bet: <<textbox "$moneybet" "0">>
    
    <<click "Calculate New Balance">>
    	<<if isNaN($moneybet)>>
    		<<set $moneybet to 0>>
    	<<else>>
    		<<set $moneybet to parseFloat($moneybet)>>
    	<</if>>
    	<<set $balance += $moneybet>>
    	<<replace "#balance">>$balance<</replace>>
    <</click>>
    
Sign In or Register to comment.