Question

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
Was it helpful?

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

OTHER TIPS

If you had a long blacklist, you would convert it to a table keyed by the list entries. A short blacklist can easily be checked by string matching:

if (" "..blacklist.." "):find( " "..player_name.." ", 1, true ) then
    doSomething()
end

The last parameter to find turns on plain string matching for find.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top