1

I am trying to make a sorting function and I need to remove duplicates from a table/array so I can get the top 3, but when I do so, it changes the original table/array.

function removeDuplicates(list)

    input = list
    i = 0
    while i < #input
    do
        if input[i] == input[i + 1] then
            table.remove(input, i)
        else
            i = i + 1
        end
    end
    
    return input
end

Is there some smart, proper way of doing this? Can I iterate over the array and set every value to a new array?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Fredrik
  • 33
  • 5
  • There is only one table (there is no “new” or “original”) so the same table is changed. Neither assignment (=) nor passing a table to a function make a new table / a copy of a table. https://stackoverflow.com/q/640642/2864740 , https://www.lua.org/pil/2.5.html – user2864740 Dec 26 '21 at 05:16
  • 1
    In this case, it would probably be easiest simply to create a *new* result table and then only *copy* what there is to keep into it: `local results = {}; add_rows_to_keep; return results` – user2864740 Dec 26 '21 at 05:20
  • 1
    I voted to reopen, because the question is really asking how to create a *modified* table, not an exact copy. @user2864740 's comment would make a good answer. – luther Dec 27 '21 at 13:47

0 Answers0