What is string.pack() and string.packsize()?

  1. What do you want to achieve?

I want to know what is string.pack() and string.packsize() is and when to use it and how to use it.

  1. What is the issue?

There are virtually no Api’s or docs on it. Plus no one will tell me what it is.

  1. What solutions have you tried so far?

I looked on Devforum and in discords.

Is this how I use it? No.

local String = "Hello World!"
print(string.pack(String, 10, ...))

So if anyone can give me an example on how to use it then that would be great.

Not exactly sure myself but you can try to look here

Tried looking there did not help.

I did some poking around - it appears to create a binary-formatted string representation of whatever arguments you provide, in the format you provide.

So, let’s say we have these arguments

local playerSize = 7
local playerName = "Bob_TheBuilder"
local playerWasKilled = false

local encodedString = string.pack("HxxzxxB", playerSize, playerName, (playerWasKilled and 1 or 0))

print(encodedString)
--> aBob_TheBuilder

for i = 1, encodedString:len() do 
   print(encodedString:sub(i,i):byte()) 
end
--> 7, 0, 0, 0, 66, 111, 98, 95, 84, 104, 101, 66, 117, 105, 108, 100 ,101, 114, 0, 0, 0, 0

So the use case of this is serializing data into a binary string (packing the arguments) and then deserializing them (unpacking the arguments). So, perhaps storing some player data in a DataStore in a compressed manner.

6 Likes

Datastores use JSON, so using a binary format doesn’t work with them. (must be a valid utf8 string, and control characters except 7F as well as \ and " get expanded to multiple bytes)

It would be useful for something like passing large quantities of data across the network.

sidenote: :sub(i,i):byte() could be :byte(i)

4 Likes