Compile Lua without automatic conversion between strings and numbers
Asked Answered
U

1

8

Lua is generally a strongly-typed language, providing almost no implicit conversion between data types.

However, numbers and strings do get automatically coerced in a few cases:

Lua provides automatic conversion between string and number values at run time. Any arithmetic operation applied to a string tries to convert this string to a number, following the rules of the Lua lexer. (The string may have leading and trailing spaces and a sign.) Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format

Thus:

local x,y,z = "3","8","11"
print(x+y,z)  --> 11   11
print(x+y==z) --> false
print(x>z)    --> true

I do not want this. How can I recompile the Lua interpreter to remove all automatic conversion?

I would prefer to have:

print(x+y)    --> error: attempt to perform arithmetic on a string value
print(x>1)    --> error: attempt to compare number with string
print(x..1)   --> error: attempt to concatenate a number value
Urumchi answered 5/3, 2014 at 23:36 Comment(6)
Doable, but not out of the box. You'll have to edit the innards of Lua. Start at lua.org/source/5.2/lvm.c.html#luaV_tonumber.Dishpan
You might want to "fix" cases like this, too: print("one="..1)Cloudburst
Is creating your own dialect of lua, subtly (and silently!) different from mainstream really worth it?Underlayer
@Underlayer Well, we've already compiled with 32-bit numbers instead of 64-bit, which has its own subtle implications (e.g. os.time() does not increase every second). That was supported by compile-time flags, though.Urumchi
Can you please explicitly state which output you'd want (for your respective examples)?Urata
@Urata Edited to add the desired output.Urumchi
U
2

The illustrious LHF has commented above that this is not possible out of the box, and requires editing the innards of Lua, starting with http://www.lua.org/source/5.2/lvm.c.html#luaV_tonumber

Marking this as the answer in order to close this question. If anyone later chooses to provide an answer with in-depth details on what needs to be done, I will gladly switch the acceptance mark to that answer.

Urumchi answered 22/4, 2014 at 15:36 Comment(1)
Agree, parameters get evaluated before being passed to the function, in this case "print". Hence the inner functioning of expression evaluation (IE coercion) needs to be changed.Urata

© 2022 - 2024 — McMap. All rights reserved.