# How does Lua round non-integer numbers in standard library ?

4 messages
Open this post in threaded view
|

## How does Lua round non-integer numbers in standard library ?

 Hi everyone- I'm Marco Mastropaolo, a programmer who - for as a hobby - is trying to create a Lua interpreter in C# with the intent of an as much "clean room implementation" as feasible (that is, implementing my grammar, interpreter, VM etc. instead of plainly converting the standard ones). I know, weird hobby.For this reason, I'm trying to analyze those little details of the standard implementations which are not specified in the documentation..One thing I don't get is how Lua rounds numbers when performing operations on the standard library.For example, on my machine:> return select(2, 1, 2, 3, 4, 5, 6, 7)2       3       4       5       6       7> return select(2.2, 1, 2, 3, 4, 5, 6, 7)2       3       4       5       6       7> return select(2.8, 1, 2, 3, 4, 5, 6, 7)3       4       5       6       7Given this, I deduced a rounding to nearest integer (confirmed for negative numbers).However a few cases are curious:> return select(2.5, 1, 2, 3, 4, 5, 6, 7)2       3       4       5       6       7> return select(2.50001, 1, 2, 3, 4, 5, 6, 7)2       3       4       5       6       7> return select(2.5001, 1, 2, 3, 4, 5, 6, 7)2       3       4       5       6       7> return select(2.501, 1, 2, 3, 4, 5, 6, 7)3       4       5       6       7At this point, I fell into temptation of peeking at the source.. and the conversion should be truncating (they are just type casts) unless some non-portable tricks are played with the machine floating point state register.Does anyone know what's going on ? I'm confused :)Thanks!-- Marco
Open this post in threaded view
|

## Re: How does Lua round non-integer numbers in standard library ?

 2014-10-09 18:42 GMT+02:00 Marco Mastropaolo <[hidden email]>: > Hi everyone > - I'm Marco Mastropaolo, a programmer who - for as a hobby - is trying to > create a Lua interpreter in C# with the intent of an as much "clean room > implementation" as feasible (that is, implementing my grammar, interpreter, > VM etc. instead of plainly converting the standard ones). I know, weird > hobby. > > For this reason, I'm trying to analyze those little details of the standard > implementations which are not specified in the documentation.. > > One thing I don't get is how Lua rounds numbers when performing operations > on the standard library. > ... >> return select(2.5, 1, 2, 3, 4, 5, 6, 7) This is illegal now. Lua 5.3.0 (alpha)  Copyright (C) 1994-2014 Lua.org, PUC-Rio > select(2.5, 1, 2, 3, 4, 5, 6, 7) stdin:1: bad argument #1 to 'select' (number has no integer representation) stack traceback:     [C]: in function 'select'     stdin:1: in main chunk     [C]: in ? In Lua 5.2.3, the manual does not say, i.e. what happens is undefined.