lua_isstring() 检查 Lua 中的真实字符串
lua_isstring() check for real strings in Lua
int lua_isstring (lua_State *L, int index);
This function returns 1 if the value at the given acceptable index is
a string or a number (which is always convertible to a string), and 0
otherwise. (Source)
是否有一种(更优雅的)方法来真正证明给定的字符串真的是一个字符串并且不是 Lua?这个功能对我来说完全没有意义!
我的第一个想法是用
额外检查字符串长度
`if(string.len(String) > 1) {/* this must be a string */}`
...但这并不感觉那么好。
你可以替换
lua_isstring(L, i)
其中 returns 对于字符串或数字为真
lua_type(L, i) == LUA_TSTRING
仅对实际字符串产生 true。
同样,
lua_isnumber(L, i)
returns 对于数字或可以转换为数字的字符串都为真;如果你想要更严格的检查,你可以将其替换为
lua_type(L, i) == LUA_TNUMBER
(我写了包装函数,lua_isstring_strict()
和 lua_isnumber_strict()
。)
This function makes absolutely no sense to me!
根据 Lua 的 coercion rules,这是有道理的。任何接受字符串的函数也应该接受数字,将数字转换为字符串。这就是语言语义的定义方式。 lua_isstring
和 lua_tostring
的工作方式允许您在 C 绑定中自动实现这些语义,无需额外的努力。
如果您不喜欢这些语义并希望禁用字符串和数字之间的自动转换,您可以在构建中定义 LUA_NOCVTS2N
and/or LUA_NOCVTN2S
。特别是,如果您定义 LUA_NOCVTN2S
,lua_isstring
将为数字 return false。
int lua_isstring (lua_State *L, int index);
This function returns 1 if the value at the given acceptable index is a string or a number (which is always convertible to a string), and 0 otherwise. (Source)
是否有一种(更优雅的)方法来真正证明给定的字符串真的是一个字符串并且不是 Lua?这个功能对我来说完全没有意义!
我的第一个想法是用
额外检查字符串长度 `if(string.len(String) > 1) {/* this must be a string */}`
...但这并不感觉那么好。
你可以替换
lua_isstring(L, i)
其中 returns 对于字符串或数字为真
lua_type(L, i) == LUA_TSTRING
仅对实际字符串产生 true。
同样,
lua_isnumber(L, i)
returns 对于数字或可以转换为数字的字符串都为真;如果你想要更严格的检查,你可以将其替换为
lua_type(L, i) == LUA_TNUMBER
(我写了包装函数,lua_isstring_strict()
和 lua_isnumber_strict()
。)
This function makes absolutely no sense to me!
根据 Lua 的 coercion rules,这是有道理的。任何接受字符串的函数也应该接受数字,将数字转换为字符串。这就是语言语义的定义方式。 lua_isstring
和 lua_tostring
的工作方式允许您在 C 绑定中自动实现这些语义,无需额外的努力。
如果您不喜欢这些语义并希望禁用字符串和数字之间的自动转换,您可以在构建中定义 LUA_NOCVTS2N
and/or LUA_NOCVTN2S
。特别是,如果您定义 LUA_NOCVTN2S
,lua_isstring
将为数字 return false。