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