38

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?

2
  • Just a note, I wouldn't get started with Lua programming with Garry's Mod. It uses questionable coding styles (parenthesis in if statements), unstandardized syntax (!, ||, && aliases for not, or, and and), and has a pretty bad API (randomly replacing builtins like require and loadstring, FooEx functions, etc.). Dec 24, 2014 at 17:23
  • Lua is not C, you don't need if-condition in brackets. It is redundant. Dec 24, 2014 at 19:32

4 Answers 4

48

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.

3
  • 12
    '==' 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. Dec 24, 2014 at 23:42
  • 1
    That's a very good catch indeed - I didn't know about the interning part. Thanks.
    – lisu
    Dec 25, 2014 at 1:17
  • 1
    @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.
    – siffiejoe
    Dec 25, 2014 at 5:16
12

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.

4

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

1

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.