Clarification: reworded a paragraph based on comments from zeux

This commit is contained in:
Petri Häkkinen 2023-02-15 13:27:45 +02:00
parent fc9b14ce69
commit 483b4eb5da

View file

@ -12,7 +12,7 @@ Luau is generally well suited to work with integers. The math operators +, -, \*
To overcome this, typical Luau code performing integer computations needs to wrap the result of division inside a call to `math.floor`. This has a number of issues and can be error prone in practice.
A typical mistake is to forget to use `math.floor`. This can produce subtle issues ranging from slightly wrong results to program crashes. A crash could occur, for example, when the result of division is used to fetch from a table with only integer keys, which produces nil and the program crashes soon after. Another type of crash occurs when an accidental fractional number is passed to a C function that expects integers. Particularly problematic is incorrect code which seems to work with frequently used data, only to fail with some rare input. For example, image sizes often have power of two dimensions, so code dealing with them may appear to work fine until much later some rare image has an odd size and a division by two in the code does not produce the correct result. Due to better ergonomics of the floor division operator, it becomes a second nature to write `//` everywhere when integers are involved and thus this class of bugs is much less likely to happen.
A typical mistake is to forget to use `math.floor`. This can produce subtle issues ranging from slightly wrong results to script errors. A script error could occur, for example, when the result of division is used to fetch from a table with only integer keys, which produces nil and a script error happens soon after. Another type of error occurs when an accidental fractional number is passed to a C function. Depending on the implementation, the C function could raise an error (if it checks that the number is actually an integer) or cause logic errors due to rounding. Particularly problematic is incorrect code which seems to work with frequently used data, only to fail with some rare input. For example, image sizes often have power of two dimensions, so code dealing with them may appear to work fine until much later some rare image has an odd size and a division by two in the code does not produce the correct result. Due to better ergonomics of the floor division operator, it becomes a second nature to write `//` everywhere when integers are involved and thus this class of bugs is much less likely to happen.
Another issue with using `math.floor` as a workaround is that code performing a lot of integer calculations is harder to understand, write and maintain.