Zack Lee
Zack Lee

Reputation: 3044

How to pass table to a function without first element?

I'm trying to create a function that receives a table of strings and parses the table to other function based on its first element.

My Code :

fruits = {}

function addToFruits(t)
print(#t)
end

function parseTable(t)
  if t[1] == "fruits" then
    addToFruits(table.remove(t, 1)) --pass only {"apple", "banana"}
  end
end

parseTable({"fruits", "apple", "banana"})

The Result I get :

6

The Result I expect :

2

How to properly parse the table without the first element?

Upvotes: 3

Views: 154

Answers (2)

wsha
wsha

Reputation: 964

The table.remove function removes (and returns) an element from a given position in an array. ref

function parseTable(t)
  if t[1] == "fruits" then
      local removed = table.remove(t, 1)
      print(removed) -- fruits
      addToFruits(t) -- fruits removed and will pass {"apple", "banana"}
  end
end

The answer 6 was the length of "fruits" which table.remove(t, 1) will return

Upvotes: 3

mksteve
mksteve

Reputation: 13073

The return value from table.remove is the removed element ("fruits" )

The object is a string and has length 6, explaining the answer your code is getting.

If you wanted the right answer 2, then the following code will do it.

fruits = {}

function addToFruits(t)
  print(#t)
end

function parseTable(t)
  if t[1] == "fruits" then
    table.remove(t, 1)
    addToFruits( t ) --pass only {"apple", "banana"}
  end
end

parseTable({"fruits", "apple", "banana"})

Obviously this damages the original table, and depending on use, would need either a table copy - there are various articles on that.

In preference, I would use a structure such as ... message = { type = "fruits", data = { "apple", "banana" } }

Allowing for the data to be separated from the message type.

The new code would look like....

fruits = {}

function addToFruits(t)
   print(#t)
end

function parseTable(t)
  if t.type == "fruits" then
    addToFruits( t.data ) --pass only {"apple", "banana"}
  end
end
message = { type = "fruits", data = { "apple", "banana" } }
parseTable( message )

Upvotes: 4

Related Questions