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

I was looking around, and I’ve found that many people use the pack and unpack functionality.
After further looking, I’ve found that more than just “many” people use these. I didn’t know why, so I’ve tried looking it up but haven’t found much of an answer. [table.pack()/table.unpack()]

So, I’ve come here as my last resort, in hopes to find the answer.

1 Like

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
      table.insert(arguments, arg)
local commandFunction = commands[command]

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(...)

So in short, there’s not really much importance/usage to them other than a selected few?

I used table.unpack a lot back when I was making my Lua interpreter since it’s useful for storing parameters and passing them around as if they were normal variadics.

1 Like

Mhm, it’s helpful in just a few special cases.