correctness
- Implicit narrow casting checks
- Related page: Run tests
Implicit narrow casting checks
$ nelua -i 'local n: cint local m = 10/2 n = m print(n)'
5
$ nelua -i 'local n: cint local m = 10/2.1 n = m print(n)'
narrow casting from float64 to cint failed
Aborted
$ nelua -Pwarnnarrow -i 'local n: cint local m = 10/2.1 n = m print(n)'
eval_LQv8NLtGS6M:1:38: warning: implicit narrow casting from `float64` to type `cint`
local n: cint local m = 10/2.1 n = m print(n)
^
narrow casting from float64 to cint failed
Aborted
$ nelua -Pnochecks -i 'local n: cint local m = 10/2.1 n = m print(n)'
4
$ nelua -r -i 'local n: cint local m = 10/2.1 n = m print(n)'
4
Nelua permits implicit numeric conversions that potentially lose information, emitting a runtime check to abort if they actually do so. The first one-liner passes the check, with a lossless cast from 5.0. The second one-liner fails it and triggers an abort, as 4.7619047619048 would lose information as a cint. The third one-liner shows that pragmas.warnnarrow warns - at compile-time - wherever these checks are emitted.
The checks aren't emitted by release builds, or if pragmas.nochecks is true.
Implicit conversions can be avoided with explicit casts, and truncating/flooring operators (// %%% ///) can control information loss:
$ nelua -Pwarnnarrow -i 'local n: cint local m = (@cint)(-1.9//1) n = m print(n)' -2 $ nelua -Pwarnnarrow -i 'local n: cint local m = (@cint)(-1.9///1) n = m print(n)' -1