Jozias
Jozias

Reputation: 27

Checks that a name is in the table [Lua]

I'm developing a script where, it should detect if the name of a "user" is banned. That is if he is on the banned list. I can add a "name" in the list (table that stores the list of users banned), but I could not develop the function that checks if a given name is in the banned list, if it is supposed to return a print

My script split:

function split(str, sep)
  local arg = {}
  for i, v in string.gmatch(str, string.format("[^%s]+", sep or "%s")) do
    table.insert(arg, i)
  end
  return arg
end

Upvotes: 0

Views: 739

Answers (1)

Curtis Fenner
Curtis Fenner

Reputation: 1411

You have a collection of names, and you want to know whether or not a name is in that collection.

The simplest way to organize this is a dictionary where the keys are the banned users:

local BANNED = {
    ["alpha"] = true,
    ["gamma"] = true,
}

When a key is in the table, you can get the associated value out:

print(BANNED["alpha"]) --> true

When a key is not in the table, you will get nil out of the table:

print(BANNED["beta"]) -- nil

If the collection of names is originally organized as a list of names (for example, from the output of your split function), you can iterate over that list with a for loop, adding each name to the BANNED dictionary:

local BANNED = {}
for _, name in ipairs(names) do
    BANNED[name] = true
end

Upvotes: 1

Related Questions