Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How To Use An Array In An If/Then Statement?

Asked by 3 years ago

Trying to make a script that whenever a player joins, the game check's if they're a 'member'. If they're one they get a special weapon, if not they get nothing. I have a basic understanding of Array's, however don't know how to use them in a If/Then statement.

Example of code:

local members = {'Player1', 'Player2', 'Player4'}

if player.Name in members then
    print('A Member')
else
    print('Not a Member')

1 answer

Log in to vote
3
Answered by
appxritixn 2235 Moderation Voter Community Moderator
3 years ago

tables have a built-in function for checking a table for a value / finding a value:

table API

Variant table.find ( table haystack, Variant needle, number init )

The first argument is the table you want to search. The second argument is the element you are searching the table for.

The last argument is the starting index, or the place in the table you want to start searching. If the last argument is not given, it will start searching from the beginning.

Keep in mind, if the element is NOT found, it will return nil

An example taken from the 'table' API:

local t = {"a", "b", "c", "d", "e"}
print(table.find(t, "d")) --> 4
print(table.find(t, "z")) --> nil, because z is not in the table
print(table.find(t, "b", 3)) --> nil, because b appears before index 3

In your case, you could do this:

local members = {'Player1', 'Player2', 'Player4'}

if table.find(members,player.Name) ~= nil then
    print('A Member')
else
    print('Not a Member')
0
Thank you! ercleric 24 — 3y
Ad

Answer this question