string 我可以在 lua 中检查字符串的相等性吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27633331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I check strings equality in lua?
提问by Howard Sun
Just a straight forward beginner question, I am coding Lua stuff for Garrys Mod, learning by reading wiki and other codings.
只是一个简单的初学者问题,我正在为 Garrys Mod 编写 Lua 代码,通过阅读 wiki 和其他编码来学习。
if (self.Owner:SteamID( ) == "STEAM_0:1:44037488" ) then
the above is the code I want to use, to check to see if the STEAM ID (which I believe is a string) is equal to my exact string.
上面是我想要使用的代码,用于检查 STEAM ID(我认为是一个字符串)是否等于我的确切字符串。
Is this viable? Or is there another way I should do it?
这是可行的吗?或者我应该有另一种方法吗?
回答by lisu
This should work exactly as you expect it to. In lua '==' for string will return true if contents of the strings are equal.
这应该完全按照您的预期工作。在 lua 中,如果字符串的内容相等,则字符串的 '==' 将返回 true。
As it was pointed out in the comments, lua strings are interned, which means that any two strings that have the same value are actually the same string.
正如评论中指出的那样,lua 字符串是 intern 的,这意味着任何两个具有相同值的字符串实际上是同一个字符串。
回答by Alexander Altshuler
One thing to consider while learning Lua (from www.lua.org/source/5.2/lstring.h.html):
学习 Lua 时要考虑的一件事(来自 www.lua.org/source/5.2/lstring.h.html):
/*
** as all string are internalized, string equality becomes
** pointer equality
*/
#define eqstr(a,b) ((a) == (b))
String comparison in Lua is cheap, string creation may be not.
Lua 中的字符串比较便宜,字符串创建可能不是。
回答by Oliver
According to http://wiki.garrysmod.com/page/Player/SteamID, SteamID()
returns a string so you should be able to write
根据http://wiki.garrysmod.com/page/Player/SteamID,SteamID()
返回一个字符串,所以你应该能够写
if self.Owner:SteamID() == "STEAM_0:1:44037488" then
...do stuff...
end
If you ever need to confirm the type of an object, use type
and print
, like in this case print('type is', type(self.Owner:SteamID()))
should print 'type is string'.
如果您需要确认对象的类型,请使用type
and print
,在这种情况下 print('type is', type(self.Owner:SteamID()))
应该打印“type is string”。