Search code examples
stringlualua-patterns

How to check for occurence of name in string?


I have a list of names separated by space in one variable like this:

blacklist = "name1 name2 name3 etc"

What I want is to check existing of some specified name in this list. Like

if nameInBlacklist("player_name") == true then
        dosomething()
end

Solution

  • Suppose that the name you want to find is in the string name, you can use:

    if (" " .. blacklist .. " "):find(" " .. name .. " ", 1, true) then
      -- do something
    end
    

    Note that the fourth parameter true is to turn off pattern matching facilities, so that it's OK for name to contain some special characters that need to escape.

    If you need to use a function:

    function nameInBlacklist(name)
      return (" " .. blacklist .. " "):find(" " .. name .. " ", 1, true)
    end
    

    Don't compare the return value with true, just use it as the condition directly:

    if nameInBlacklist("player_name") then
      --do something
    end