Search code examples
lua

Determining if a variable is from a list of several values in Lua


I'm trying to figure out an easier way to determine if a variable is one of several values in Lua. In this case, I'm trying to check if variable Player.Name is equal to "Player1", "Player2" or "Player3" (example names), and then change the variable image.Image:

This code works:

        if Player.Name == "Player1" or Player.Name == "Player2" or Player.Name == "Player3" then
            image.Image = "rbxassetid://4743025782"
        else
            image.Image = "rbxassetid://0"
        end

but I hate doing this for every Player.Name I have to add, so I'm wondering if there's a better way to do this.


Solution

  • You can make a lookup table also known as set.

    local AllowedPlayerNames = {
        Player1 = true,
        Player2 = true,
        Player3 = true
    }
    
    if AllowedPlayerNames[Player.Name] then -- If `Player.Name` is in AllowedPlayerNames it returns its value, which is `true`.
        image.Image = "rbxassetid://4743025782"
    else
        image.Image = "rbxassetid://0"
    end
    

    lookup table is a regular table but the keys are the accepted values and value can be any value, we need truthy value to make if statement to work, so true is fine.

    Note: You can write string keys as variables if they follow Lua's naming conventions

    Names (also called identifiers) in Lua can be any string of Latin letters, Arabic-Indic digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels.

    If you have different type or string with other characters use this syntax:

    ["Player1"] = true (this is the same as Player1 = true)