문제

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
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top