Howdy, Stranger!

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

How do I limit a variable?

I have used the search function so pardon me if the question has been asked but I have several variables that increase or decrease (numerical, like an rpg) but I want to prevent them from going above or below a certain number. Is this possible? If so, how?

Comments

  • edited November 2015
    Which story format are you using? How are you modifying the $variables?

    Anyway, limiting a value to a specific range is known as clamping. The simple answer would be to check the value afterwards and, if it exceeds your specified range in a particular direction, reset it to the min/max.

    For example, let's assume a range of [2, 10].


    The following works in all Twine 1 story formats and SugarCube:

    Clamping after modification, using <<if>> and <<set>>:
    → Modify the value.
    <<set $stat += 1>>
    
    → Clamp it.
    <<if $stat lt 2>><<set $stat to 2>><<elseif $stat gt 10>><<set $stat to 10>><<endif>>
    
    However, you could also clamp during modification, using Math.min() and Math.max():
    → Modify the value and clamp it in one go.
    <<set $stat to Math.max(2, Math.min($stat + 1, 10)>>
    


    Beyond that, SugarCube has a few clamping methods available:

    Clamping after modification:
    → Modify the value.
    <<set $stat += 1>>
    
    → Clamp it.
    <<set $stat to $stat.clamp(2, 10)>>
    
    Or, again, you could also clamp during modification:
    → Modify the value and clamp it in one go.
    <<set $stat to Math.clamp($stat + 1, 2, 10)>>
    
Sign In or Register to comment.