【问题标题】:Trying to build a table of unique values in LUA尝试在 LUA 中构建唯一值表
【发布时间】:2020-06-25 02:43:39
【问题描述】:

我正在尝试构建一个表并在每次我得到一个尚未在表中的返回值时添加到它。所以基本上我到目前为止所拥有的根本不起作用。我是 LUA 新手,但不是一般的编程新手。

local DB = {}
local DBsize = 0

function test()
  local classIndex = select(3, UnitClass("player")) -- This isn't the real function, just a sample
  local cifound = False

  if classIndex then
    if DBsize > 0 then
      for y = 1, DBsize do
        if DB[y] == classIndex then 
          cifound = True
        end
      end
    end

    if not cifound then 
      DBsize = DBsize + 1
      DB[DBsize] = classIndex
    end
  end
end

然后我尝试使用另一个函数来打印表格的内容:

        local x = 0

        print(DBsize)
        for x = 1, DBsize do
            print(DB[x])
        end 

任何帮助将不胜感激

【问题讨论】:

标签: lua lua-table


【解决方案1】:

只需使用您的唯一值作为键在表中存储一个值。这样您就不必检查值是否已经存在。如果您有第二次,您只需覆盖任何现有的密钥。

存储来自 100 个随机值的唯一值的简单示例。

local unique_values = {}

for i = 1, 100 do
  local random_value = math.random(10)
  unique_values[random_value] = true
end

for k,v in pairs(unique_values) do print(k) end

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2021-04-28
    • 2018-12-25
    • 1970-01-01
    相关资源
    最近更新 更多