-2

I have a list of indexes I need my users to input, and I need the code to check if any of them are repeated, so it would give an error (they cannot be repeat).

if i only had two indexes it would be simple as :

if indexa == indexb then error() end

but its a fairly long list.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Mojimi
  • 2,561
  • 9
  • 52
  • 116

2 Answers2

1

Here's a basic algorithm for detecting repeats.

-- 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

In other words, table keys cannot be repeated, so you can simply store any non-nil value in a table under that key. Later (in future iterations of the loop), you can check to see whether that key is nil.

luther
  • 5,195
  • 1
  • 14
  • 24
0

You could put all the indices in a table, use table.sort to sort them, then loop over table items to test if any consecutive items are identical:

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
Oliver
  • 27,510
  • 9
  • 72
  • 103