When will I ever use table.pack() and table.unpack()

When will I ever use table.pack() and table.unpack()?

or do I not use them at all?

As much as I know, table.pack() is used for converting a data into JSON code, so it can be used when you want to serialize things, and use table.unpack to convert it back into a Lua Table and deserialize it.

It just appears to add stuff into a table while adding the index for the number of stuff, and remove stuff from the table.

I know this is an awkward answer, but you will use them when you need them :sweat_smile:

Their purposes is to convert arrays to and from variadics.

If a function returns a tuple with an unknown number of items, you should pack it into a table not to lose any data. You can also pack variadics to get a specific element.

Here is an example:

function x()
    return 1, 2, 3, 4
end

local packed = table.pack(x())
print(x) -- {1, 2, 3, 4}
print(#x) -- 4
print(x[3]) -- 3

print(table.maxn(table.pack(1,nil,nil,nil,nil,456))) -- 6

print(table.unpack({"Hello", nil, 123})) -- Hello   123

When you do encounter this problem, they will become very useful. If you don’t see a need for it, don’t use it!

More info here: Lua 5.3 Reference Manual

IGNORE. ONLY HERE FOR COMMENT HISTORY [quote="Moneypro456789, post:2, topic:2207816, full:true"] As much as I know, table.pack() is used for converting a data into JSON code, so it can be used when you want to serialize things, and use table.unpack to convert it back into a Lua Table and deserialize it. [/quote]

Stop using ChatGPT. If you didn’t use ChatGPT, then at least fact-check your information before you post misinfo online.
EDIT: Maybe you mean string.pack? But that doesn’t serialize to JSON…

EDIT: User has stated they did not use ChatGPT, just misinformed.

2 Likes

Ah, that makes sense.

Speaking of this, dont you have to encode it using HttpService for it to be JSON?

Yes. Which is also a Roblox service and has nothing to do with built-in Lua(u)

1 Like

What ? ChatGPT ??? I wrote this on my own dude. Don’t put wrong allegations. Also, I wrote “As much as I know”, so I clearly stated I maybe wrong. But think before putting wrong allegations. And atleast ChatGPT can give the answer right, but I wrote it on my own. Sorry I may got rude here, but still I wrote on my own, this is the real fact.

2 Likes

nah.

My apologies. In hindsight, it is quite obvious thay you didn’t use ChatGPT but I’ve seen it so commonly used by trolls I assumed you were one.

Anyway, I apologize for this and I will edit my initial post.

Sorry for the bother.

EDIT: Removed unnecessary “justification” on my part

1 Like

I actually can’t get more usage of it, because it’s obvious that when you need it, use it, it don’t have much applications I guess, it’s just convert arrays into varadics as stated by @majdTRM

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.