Lua编译时,如何避免自动将字符串和数字间转换?

2026-04-01 19:141阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计339个文字,预计阅读时间需要2分钟。

Lua编译时,如何避免自动将字符串和数字间转换?

Lua通常是一种强类型语言,几乎不提供数据类型之间的隐式转换。但是,数字和字符串确实在少数情况下会自动转换:Lua在运行时自动在字符串和数字值之间进行转换。

Lua通常是一种 strongly-typed语言,几乎不提供数据类型之间的隐式转换.

但是,数字和字符串确实得到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

从而:

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

我不想要这个.如何重新编译Lua解释器以删除所有自动转换?

我更愿意:

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 杰出的 LHF在上面评论说这不是开箱即用的,需要编辑Lua的内部,从 www.lua.org/source/5.2/lvm.c.html#luaV_tonumber开始

将此标记为答案以便结束此问题.如果有人后来选择提供有关需要做什么的深入细节的答案,我很乐意将接受标记切换到该答案.

Lua编译时,如何避免自动将字符串和数字间转换?

本文共计339个文字,预计阅读时间需要2分钟。

Lua编译时,如何避免自动将字符串和数字间转换?

Lua通常是一种强类型语言,几乎不提供数据类型之间的隐式转换。但是,数字和字符串确实在少数情况下会自动转换:Lua在运行时自动在字符串和数字值之间进行转换。

Lua通常是一种 strongly-typed语言,几乎不提供数据类型之间的隐式转换.

但是,数字和字符串确实得到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

从而:

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

我不想要这个.如何重新编译Lua解释器以删除所有自动转换?

我更愿意:

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 杰出的 LHF在上面评论说这不是开箱即用的,需要编辑Lua的内部,从 www.lua.org/source/5.2/lvm.c.html#luaV_tonumber开始

将此标记为答案以便结束此问题.如果有人后来选择提供有关需要做什么的深入细节的答案,我很乐意将接受标记切换到该答案.

Lua编译时,如何避免自动将字符串和数字间转换?