Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 如何将一组值与它们自己进行比较_Lua_Lua Table - Fatal编程技术网

Lua 如何将一组值与它们自己进行比较

Lua 如何将一组值与它们自己进行比较,lua,lua-table,Lua,Lua Table,我有一个需要用户输入的索引列表,我需要代码来检查其中是否有重复的索引,因此它会给出一个错误(它们不能重复) 如果我只有两个索引,它将很简单: if indexa == indexb then error() end 但这是一个相当长的列表。您可以将所有索引放在一个表中,使用table.sort对它们进行排序,然后循环表项以测试是否有任何连续项相同: indices = {1,6,3,0,3,5} -- will raise error indices = {1,6,3,0,4,5} -- wi

我有一个需要用户输入的索引列表,我需要代码来检查其中是否有重复的索引,因此它会给出一个错误(它们不能重复)

如果我只有两个索引,它将很简单:

if indexa == indexb then error() end

但这是一个相当长的列表。

您可以将所有索引放在一个表中,使用
table.sort
对它们进行排序,然后循环表项以测试是否有任何连续项相同:

indices = {1,6,3,0,3,5} -- will raise error
indices = {1,6,3,0,4,5} -- will not raise error
table.sort(indices)
for i=1, (#indices-1) do 
    if indices[i] == indices[i+1] then
        error('not allowed duplicates')
    end
end

这里有一个检测重复的基本算法

-- This table is what's known as a set.
local indexes = {}

while true do
  local index = getIndexFromUser()

  -- Check for end of input.
  if not index then
    break
  end

  -- Check for repeats.
  if indexes[index] then
    error()
  end

  -- Store index as a key in indexes.
  indexes[index] = true
end
换句话说,表键不能重复,所以您可以简单地将任何非nil值存储在该键下的表中。稍后(在循环的未来迭代中),您可以检查该键是否为nil