Search code examples
lualua-table

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?


Solution

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