Why use [table] pack() and unpack()?

I only use these functions for situations where I want to do something with multiple (or an unknown amount of) values in a table. I don’t use them a lot usually, only in the rare cases where either I’m dealing with something tedious or don’t know the number of arguments.

For example, printing the contents of an array (this is pretty useful since Lua doesn’t print a table’s contents by default):

print(table.unpack({"Tree", "Rock", "Flower"}))

Or passing multiple values into a function when making admin commands:

local arguments = {}
local command
for _, arg in string.gmatch(chatMessage, "[^%s]+ ") do
   if not command then
      command = arg
   else
      table.insert(arguments, arg)
   end
end
local commandFunction = commands[command]
commandFunction(table.unpack(arguments))

An unknown amount of arguments can be used by the recieving functions using the ... symbol like so (this is the only case where I have ever found table.pack useful since you can just do {value1, value2} with less writing):

local function doSomething(arg1, ...)
   local otherArgs = {...} -- alternative syntax for table.pack(...)
   print(otherArgs[1])
end
10 Likes