All Questions


Erik Shuttlesworth

Off-by-one Error

Because rand_range function's second parameter is an exclusive upper bound, and int() rounds down, the "- 1" in

$Sprite.region_rect = REGIONS[int(rand_range(0, REGIONS.size() - 1))]

BranchesEntity and StoneEntity leaves out the last sprite.

  • Razoric replied

    Looking at RandomNumberGenerator's class, the documentation cites all of the rand functions as being inclusive. Following its code in the C++ Godot source code reveals that it calls RandomPCG's random functions.

    Going to rand_range() on @GDScript reveals it calls Math::random from math_funcs, which calls a RandomPCG "default_rand" object's random functions.

    If RandomNumberGenerator's documentation is accurate, then that should make rand_range's upper bounds also inclusive.


    Though it's kind of pedantic. It is true that to get the last sprite we'd need to hit the maximum value, which isn't quite as likely. The proper code would be to generate it at size() and clamp it on the off chance we do hit it. Even better would be to use RandomNumberGenerator's randi_range() though.

  • S
    Erik Shuttlesworth replied

    Ah, I got thrown off by the range() function's bounds. I wish the documentation was clearer about that. (I suppose I could submit a PR to fix that...) Thank you for the detailed explanation.