Declaring positive integers (unsigned int)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Greenpk

Hello,

I have been programming C++ for a while now and realized it might be more efficient to turn to GDScript now that I want to start developing a game I have in mind.

From what I realized is that GDscript lacks the unsigned integer variable type, which I find very unsafe.

For example Currency in a game, it would be decent if it could only remain positive when defined.
Instead of having to check using if-statements everytime the variable is used, to ensure it won’t drop below 0 at any point.

I struggled figuring out any reasonable answer to this through google and documentation.
I would greatly appreciate if there is solutions to this.

If you are actually worried about your Currency value going negative, it is better to use a signed integer, since that allows you to detect that it went negative. The failure mode of a signed integer Currency going negative is also safer, since subsequent checks for whether the player can purchase something will indicate they can’t.

If you use an unsigned integer and a mistake in the code subtracts more currency than there was, then you end up with a very large positive number and then even correct code will allow the player to purchase anything.

Generally, you should only have two functions that manipulate your currency - one function to add money the player finds/earns/steals/etc and one function to subtract money the player spends. The function that subtracts should check that there is enough money available before subtracting and return indicating a failure if there isn’t enough money. It should also make sure you aren’t subtracting a negative amount. Then you only need to check in one place.

cheese65536 | 2021-03-29 16:26

:bust_in_silhouette: Reply From: exuin

I guess you could use the clamp() function but it doesn’t appear that GDScript has an unsigned int