在Lua中确定变量是否来自一组多个值

我正在尝试找出一种更简单的方法来确定在Lua中变量是否是一组多个值中的一个。 在这种情况下,我正在尝试检查变量 Player.Name 是否等于 "Player1""Player2""Player3"(示例名称),然后更改变量image.Image

这段代码有效:

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

但我讨厌为每个要添加的 Player.Name 这样做,所以我想知道是否有更好的方法。

点赞
用户8621712
用户8621712

你可以创建一个查找表,也称为“设置”(set)。

local AllowedPlayerNames = {
    Player1 = true,
    Player2 = true,
    Player3 = true
}

if AllowedPlayerNames[Player.Name] then -- 如果 `Player.Name` 在 AllowedPlayerNames 中,则返回它的值,即 `true`。
    image.Image = "rbxassetid://4743025782"
else
    image.Image = "rbxassetid://0"
end

查找表(lookup table)是一个普通的表,但键是可接受的值,而值可以是任何值,我们需要一个真值来使if语句起作用,因此使用true是可以的。

注意:如果要使用字符串作为键并遵循Lua的命名规则(https://www.lua.org/manual/5.4/manual.html#3.1),可以将其写成变量形式。

Lua中的名称(也称为标识符)可以是任何由拉丁字母、阿拉伯印度数字和下划线组成且不以数字开头并且不是保留字的字符串。标识符用于名称变量、表字段和标签。

如果您有不同类型或带有其他字符的字符串,请使用此语法:

["Player1"] = true (这与 Player1 = true 相同)

2021-01-28 13:03:29
用户2858170
用户2858170

你可以使用查找表来为特定名称定义图像,如果名称未列出则默认为另一个图像。

local playerImages = setmetatable({
    ["Han Solo"] = "rbxassetid://4743025782",
    ["Luke Skywalker"] = "rbxassetid://4743025782",
  }, {
     __index = function() return "rbxassetid://0" end})

local playerName1 = "Han Solo"
local playerName2 = "Mickey Mouse"
print(playerImages[playerName1])
print(playerImages[playerName2])

或者,如果玩家图像是特定于玩家的,则将其作为每个玩家的属性,然后在需要时使用 Player.Image 之类的东西。

或者创建图像字符串列表:

local images = {
  [1] = "image1",
  [2] = "image2",
  default = "defaultImage"}

local playerImg = {
  ["Player1"] = 1,
  ["Player2"] = 2,
}

local imgIndex = playerImg[PlayerName]
local img = playerImg[imgIndex] or playerImg.default
2021-01-28 13:39:49