Can I check strings equality in lua?
Solution 1
This should work exactly as you expect it to. In lua '==' for string will return true if contents of the strings are equal.
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.
Solution 2
One thing to consider while learning Lua (from 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.
Solution 3
According to http://wiki.garrysmod.com/page/Player/SteamID, SteamID()
returns a string so you should be able to write
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'.
Solution 4
In lua, as answered above, '==' checks for equality. Not saying you did this, because you didnt, but a common mistake is thinking that '=' is equality. '=' is assignment, '==' is equality.
Admin
Updated on December 30, 2021Comments
-
Admin over 2 years
Just a straight forward beginner question, I am coding Lua stuff for Garrys Mod, learning by reading wiki and other codings.
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.
Is this viable? Or is there another way I should do it?
-
user3125367 over 9 years'==' is actually identity comparison and not char-by-char (unless intentionally overloaded). But all Lua strings are interned, so equal strings are always identical and equality test costs nothing.
-
lisu over 9 yearsThat's a very good catch indeed - I didn't know about the interning part. Thanks.
-
siffiejoe over 9 years@user3125367: Starting with Lua 5.2.1 this is no longer true as strings longer than 40 characters are not interned any more. Lua still does The Right Thing in this case, which is character-by-character comparison. I don't know which Lua version Garry's Mod uses.
-
Lorraine R. over 2 yearsThis does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review