Howard Sun
Howard Sun

Reputation: 419

Can I check strings equality in lua?

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?

Upvotes: 41

Views: 102279

Answers (4)

Chiptunes
Chiptunes

Reputation: 11

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.

Upvotes: 0

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

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.

Upvotes: 12

lisu
lisu

Reputation: 2263

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.

Upvotes: 53

Oliver
Oliver

Reputation: 29591

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'.

Upvotes: 5

Related Questions