1

What is the typical approach in LUA (before the introduction of integers in 5.3) for dealing with calculated range values in for loops? Mathematical calculations on the start and end values in a numerical for loop put the code at risk of bugs, possibly nasty latent ones as this will only occur on certain values and/or with changes to calculation ordering. Here's a concocted example of a loop not producing the desire output:

a={"a","b","c","d","e"}
maybethree = 3 
maybethree = maybethree / 94
maybethree = maybethree * 94
for i = 1,maybethree do print(a[i]) end

This produces the unforuntate output of two items rather than the desired three (tested on 5.1.4 on 64bit x86):

a
b

Programmers unfamiliar with this territory might be further confused by print() output as that prints 3!

The application of a rounding function to the nearest whole number could work here. I understand the approximatation with FP and why this fails, I'm interested in what the typical style/solution is for this in LUA.

Related questions:

KevinJWalters
  • 193
  • 1
  • 7

1 Answers1

2

The solution is to avoid this reliance on floating-point math where floating-point precision may become an issue. Or, more realistically, just be aware of when you are using FP and be mindul of the precision issue. This isn’t a Lua problem that requires a Lua-specific solution.

maybethree is a misnomer: it is never three. Your code above is deterministic. It will always print just a and b. Since the maybethree variable is less than three, of course the for loop would not execute 3 times.

The print function is also behaving as defined/expected. Use string.format to show thr FP number in all its glory:

print(string.format("%1.16f", maybethree)) -- 2.9999999999999996

Still need to use calculated values to control your for loop? Then you already mentioned the answer: implement a rounding function.

brianolive
  • 1,573
  • 2
  • 9
  • 19
  • I think lua puts the naive programmer at higher risk than other languages? For example, if you try a similar thing in Python 3 with for i in range(maybethree) then it will throw a TypeError exception. – KevinJWalters Aug 26 '18 at 15:18
  • 2
    Perhaps. Thats said, it is difficult to program under the weight of too much naivete. Have to keep learning! That’s what’s great about SO. – brianolive Aug 26 '18 at 15:26
  • Does the language specification require 64 bit IEEE 754 and does it specify a rouding method, e.g. FE_TONEAREST. It feels like that would have an influence on the likelyhood of maybethree being 3. – KevinJWalters Aug 29 '18 at 16:13