Corsaka
Corsaka

Reputation: 422

"table expected, got string" when nesting tables and attempting table.remove

I'm currently attempting to create a table of tables, and removing parts from the previous nested table to make the next nested table, thereby decreasing the length of each nested table by 1.

However, upon running the code below, it triggers a bad argument #1 to 'remove' (got string, expected table) error. I can't understand why this is.

possiblePorts = {}
possiblePorts[1] = {"VGA","USB","Ethernet","9mm","HDMI"}
for i=2,5 do
  possiblePorts[i] = table.remove(possiblePorts[i-1],math.random(1,5))
end

I'm expecting it to create a table of:

possiblePorts = {
  {"VGA","USB","Ethernet","9mm","HDMI"},
  {"VGA","Ethernet","9mm","HDMI"},
  {"VGA","9mm","HDMI"},
  {"9mm","HDMI"},
  {"9mm"}
} --formatted for simple viewing

or something similar - why is it not doing so, and what can I do to fix it?

Upvotes: 2

Views: 1976

Answers (1)

Nifim
Nifim

Reputation: 5031

table.remove will return the removed element not the remaining elements of the table.

Lua 5.3 Reference Manual #table.remove

What happens in your code is the first loop works with no issues. During the second loop, possiblePorts[i-1] is now 2 so we attempt to use table.remove on the value at index 2. The value we put at index 2, in the first loop, was a string so we generate the error trying to pass it as the first arg of table.remove.

You also cannot use math.random(1,5) on each table as that gives you a risk of hitting outside the end of the array, and this will result in an error from table.remove. You want to change 5 out for the length of the array.

This code does what you were trying to accomplish

local possiblePorts = {}
possiblePorts[1] = {"VGA","USB","Ethernet","9mm","HDMI"}
for i=2,5 do
  possiblePorts[i] = {}
  local skip = math.random(1,#possiblePorts[i-1]) -- Get value we will skip at random
  local index = 0                                 -- Index for new array

  for j=1,#possiblePorts[i-1] do   -- Loop over all the elements of that last array.
    if j ~= skip then              -- If the value is not the one we are skipping add it.
      index = index + 1
      possiblePorts[i][index] = possiblePorts[i-1][j]
    end
  end
end


for k,v in ipairs(possiblePorts) do
  print(k, "{" .. table.concat(v," ") .. "}")
end

Output:

1   {VGA USB Ethernet 9mm HDMI}
2   {USB Ethernet 9mm HDMI}
3   {USB Ethernet HDMI}
4   {Ethernet HDMI}
5   {Ethernet}

Upvotes: 1

Related Questions