How would I pick multiple elements from a table without duplicates?

local t = {"value", "Another_Value", ["num"] = 1, 2, 3}

function table.shallow_copy(t)
  local t2 = {}
  for k,v in pairs(t) do
    t2[k] = v
  end
  return t2
end

function table.full_length(t)
    total = 0
    for i,v in pairs(t) do
        if v ~= nil then total+=1 end
    end
    return total
end

function pickRandoms(amount)
  local copy = table.shallow_copy(t)
  local result = {}
  for _ = 1,amount do
    local num = math.random(1,table.full_length(copy))
    local i = 0
    for index,value in pairs(copy) do
        i += 1
        if i == num then
            result[index] = value
            copy[index] = nil
        end
    end
  end
  return result
end

local result = pickRandoms(3)

you could try something like this, it basically picks a random value of the table length using the custom length function since it is a dictionary. It matches it up with a counter to then add the values to a new table and removed them from the cloned version of the original table.

1 Like