【问题标题】:How do I not add items to a table that exist in another?如何不将项目添加到另一个表中?
【发布时间】:2020-05-14 01:35:11
【问题描述】:

我正在创建一个允许 Lua 脚本的游戏服务器。基本上,脚本获取服务器日期并根据该日期选择一个文本文件。每个文本文件都包含一个名称列表。脚本的重点是将玩家重命名为“有趣”的节日名称。

这是我填充表格并分配名称的初始代码:

-- Get Names from selected Holiday file
local holFile = io.open(filePath .. holiday .. ".txt", "r");
local holidayNames = {}

for line in holFile:lines() do
    table.insert (holidayNames, line);
end

-- Set Name to a random item in the Holiday Names table
randomItem = math.random(0, #holidayNames - 1)
Name = (holidayNames[randomItem])

我还在上述代码之前添加了这部分,只是为了让一个表填充当前名称:

-- Get Current Players List
local currPlayers = io.open(filePath "players.txt", "r");
local currentPlayers = {}

for line in currPlayers:lines() do
    table.insert (currentPlayers, line);
end

所以基本上,当我尝试将项目添加到 holidayNames 时,我想首先查看它们是否存在于 currentPlayers 中。

【问题讨论】:

标签: lua


【解决方案1】:

由于 currentPlayers 已经定义,您必须扫描假日名称中的每一行以查找匹配项。您可以使用对来执行此操作:

for line in holFile:lines() do
    for __, name in pairs(currentPlayers) do
        if name ~= line then
            -- skip insertion if it's a match
            table.insert(holidayNames, line)
        end
    end
end

【讨论】:

  • 澄清一下,这个想法是获取 currPlayers,然后根据 holFile 分配一个随机名称,跳过在 currPlayers 中找到的任何名称以避免两个具有相同名称的玩家。附带说明一下,进入服务器的同名玩家已经自动重命名为通用名称,这是我想避免的。这是你的答案吗?只是确认。谢谢。
  • 哦,好吧,那这行不通。但是,如果您不关心维护holidayNames,您可以在分配后从holidayNames 中删除随机名称:holidayNames[randomItem], holidayNames[#holidayNames] = holidayNames[#holidayNames], nil 这样,holidayNames 将始终包含唯一名称并保持连续数组。如果您再次需要完整的数组,则必须重新加载它。
  • 我认为我不应该维护 holidayNames。假设一个玩家在假期的晚上 11:50 加入,然后另一个玩家在上午 12:10 加入。我不希望在午夜之后加入的玩家被重新分配一个假期名称,允许脚本在玩家加入时查找日期/时间,然后在必要时分配一个假期名称。我可能应该将 currPlayers 保存在内存中,以便能够在新玩家加入时比较两者,然后将当前玩家写入文本文件(添加/删除)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多