Roblox documentation explains what buffers are, but not how to think about them.
Hey, it’s me, Yarik; this post fills that gap.
What even is a bit? What is a byte?
- Bit = 0 or 1 (true/false)
- Byte = 8 bits
- A byte can represent 256 values (0–255)
Computers do not understand numbers, strings, booleans, or tables.
They only understand patterns of bits.
Everything else is an agreement on meaning (interpretation).
Bytes are the minimum unit (almost everywhere)
In Roblox (and most languages):
- You cannot allocate a single bit
- The smallest addressable unit is 1 byte
That’s why:
- 1 boolean = 1 byte (unless you pack bits manually)
- Buffers operate in bytes, not bits
If you want bit-level control → you pack/unpack yourself.
Buffers: what they really are
A buffer is:
A contiguous block of raw bytes with no meaning by default.
Meaning is defined externally, by you.
Example mental model:
Byte 0–3 [0,1,2,3] → PlayerId (u32)
Byte 4 [4] → Flags (bitmask aka booleans)
Byte 5–20 [5,6,7...,19,20] → Username (string)
Buffers are data layouts, not magic objects.
Visualizing bits (IMPORTANT)
Before bitwise operations make sense, you must see bits.
Here’s a helper function that visualizes a 32-bit number, grouped by bytes:
local function tobits32(n: number): string
local s = ""
for byte = 3, 0, -1 do
local b = bit32.rshift(n, byte * 8) % 256
for bit = 7, 0, -1 do
s ..= (bit32.band(b, bit32.lshift(1, bit)) ~= 0 and "1" or "0")
end
if byte ~= 0 then
s ..= "\t"
end
end
return s
end
Trivia (read this after finishing the post)
How does the visualizer works?
Bit32 equals exactly 4 bytes, and it scans bits in each byte to be 0 or 1
bit32.lshift(1, bit) generates a number with bit sequences like this every iteration:
00000001
00000010
00000100
00001000
Etc..
And since number 0 has a 00000000 byte pattern, this means there were no matches and hence writes “0” to a string but otherwise writes “1” since there was found a bit match.
For you to have mental mode:
bit32.band(0b_00101100,00000000) == 0
bit32.band(0b_00101100,00100000--[[bit32.lshift(1, 5)]]) ~= 0
0 = 00000000
1 = 00000001
Since you read this post, here is a quiz:
(bit32.band(b, bit32.lshift(1, bit)) ~= 0 and "1" or "0")
How can this line be simplified?
HINT: There is a bit32 function made just for that.
Example:
print(tobits32(10))
Result:
00000000 00000000 00000000 00001010
This is not one-sided, as since Luau (Roblox’s programming language) lets you map numbers in binary layout:
Using this format:
[0b][Bits]
Adding _ does not change anything but lets you visually separate each byte
print(0b00000000_00000000_00000000_00001010)
Result:
10
Note that this sequence would also equal 10. The declaration starts from the byte on the right side; the same with bits, every remaining bit to the left is considered as 0 automatically.
print(0b00001010)-->10
print(tobits32(0b111))-->00000000 00000000 00000000 00000111
Bit → Number Interpretation (translation)
As you may have noticed, a sequence of bits represents an actual mathematical number; this interpretation differs and acts very differently depending on the type of your number.
This interpretation essentially acts like real-world languages, where a specific word would mean one thing in one language but something different in another, but instead of words we have bit patterns here.
For example, here is the representation of what each slot of a bit represents for a u8 type number:

E.g., number = value summary of all bits that equal 1 in byte sequence; above you can see what value each bit has in the u8 number type system.
0b11000000 = 192
u8 is, as we see, pretty cheap, requiring 8 bits (or 1 byte), but its range is limited to 0-255 and can’t be negative.
For this purpose, there are other number types.
Number interpretation has a standardized naming format.
[u/i/f][bit count]
- u = Unsigned (can’t be negative)
- i = Signed (can be negative but has reduced range per direction)
- f = Floating point number (lower precision past a certain point BUT CAN BE BOTH NEGATIVE AND POSITIVE AND HAS DECIMALS!!!)
bit32 library
One way to manipulate bits is all numbers in this library will be interpreted as u32;
Recommend grabbing our handy tobits32 debug function!
Starting off with real basics and will go to more niche stuff:
bit32.band() (a & b)
This function returns the number who’s bits has passed “and” logic gate filtering
What does this mean?
Lets look at abstract table:
| Input1 | Input2 | Output |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
Basically, for a bit to pass filtering, all templates must have a bit set to 1 in this position.
print(tobits32(bit32.band(0b00000111,0b00000110,0b00000101))) --> 00000100
The 3rd bit (from right to left) was found in all 3 passed numbers there, so it has passed filtering.
bit32.bor() (a | b)
This function returns the number who’s bits has passed “or” logic gate filtering
If at least 1 of the numbers had a bit toggled in a certain position? It passes filtering.
| Input1 | Input2 | Output |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
print(tobits32(bit32.bor(0b10000111,0b00010110,0b10000100))) --> 10010111
bit32.bxor() (a ^ b)
This function returns the number who’s bits has passed “xor” logic gate filtering
To pass filtering, there has to be ONLY ONE bit with a different state in this position, which passes ONLY when both requirements are met.
| Input1 | Input2 | Output |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
print(tobits32(bit32.bxor(0b00000000,0b00000000,0b10000000,0b00000000))) --> 10000000 (fine)
print(tobits32(bit32.bxor(0b10000000,0b00000000,0b10000000,0b00000000))) --> 00000000 (not fine)
print(tobits32(bit32.bxor(0b00000000,0b10000000,0b10000000,0b10000000))) --> 10000000 (also fine)
bit32.bnot() (~a)
This function flips bits
| Input1 | Output |
|---|---|
| 0 | 1 |
| 1 | 0 |
print(tobits32(bit32.bnot(0b01011111))) --> 10100000
bit32.btest() ((a & b) != 0)
Same as bit32.band() but also checks if output ~= 0 (in actual number format)
Basically:
return bit32.band(...) ~= 0
| Input1 | Input2 | Output |
|---|---|---|
| 0 | 0 | false |
| 0 | 1 | false |
| 1 | 0 | false |
| 1 | 1 | true |
print(bit32.btest(0b01011111,0b00000001,0b00000001)) --> true
print(bit32.btest(0b01011111,0b00000000,0b00000000)) --> false
print(bit32.btest(0b00000000,0b00000000,0b00000000)) --> false
bit32.lshift() (a << n)
Shifts bits to the left ←
print(tobits32(bit32.lshift(0b00000001,4))) --> 00010000
bit32.rshift() (a >> n)
Shifts bits to the right →
print(tobits32(bit32.rshift(0b00001000,3))) --> 00000001
bit32.arshift() (a >> n (signed))
Shifts bits to the right → and preserves sign bit 31 state
Unlike bit32.rshift(), it fills “emptied” bits with a value of bit 31 (the most significant bit that corresponds to the value being negative)
print(tobits32(bit32.arshift(0b00001000,3))) --> 00000001
print(tobits32(bit32.arshift(0b00001000,3))) --> 00000001
print(tobits32(bit32.arshift(0b10000000_00000000_00000000_00000000,3))) --> 11110000 00000000 00000000 00000000
print(tobits32(bit32.arshift(0b00000000_00000000_00000000_10000000,3))) --> 00000000 00000000 00000000 00010000
Super confusing and super mind-breaking using i32 arithmetics in u32 honestly
If you reinterpret u32 returned by the bit32 library function as i32 everything makes more sense:
local val = bit32.arshift(0b10000000_00000000_00000000_10000000,3)
print(if val >= 2^31 then val-2^32 else val)--converts u32 to i32
bit32.lrotate() (rol(a, n))
“If byte range was round” as i like to call it, its bit32.lshift BUT it circles back, no data gets lost, very fun and very useful function. Data that gets out of bounds gets looped back at the start; cool right?
Do pay attention, though it is a 32-bit integer, so it loops back at the edge of bit #31 and not #7
print(tobits32(bit32.lrotate(0b10000000,31)))--[[ bro almost did 360 flip ☠
Anyway: 00000000 00000000 00000000 01000000
]]
print(tobits32(bit32.lrotate(0b10000000,32))) -- 360 flip literally, all data remained the same
bit32.rrotate() (ror(a, n))
same as bit32.lrotate() just the right side this time
print(tobits32(bit32.rrotate(0b10000000,31))) -- 00000000 00000000 00000001 00000000
print(tobits32(bit32.lrotate(0b10000000,32))) -- 360 flip literally, all data remained the same
bit32.byteswap() (bswap(a))
Reverse order of byte position, does not edit bits though only bytes
print(tobits32(bit32.byteswap(0b_00000001_00000000_00000000_00000000))) --> 00000000 00000000 00000000 00000001
print(tobits32(bit32.byteswap(0b_00000000_00000000_00000000_10000000))) --> 10000000 00000000 00000000 00000000
bit32.extract() ((a >> pos) & ((1 << len) - 1))
Extract bit field and create number with that bit field
print(tobits32(bit32.extract(0b_00000000_00000000_10000001_00000000,8,8))) --> 00000000 00000000 00000000 10000001
bit32.replace() ((a & ~mask) | ((v << pos) & mask))
Extract bit field from
v(at bit 0) and apply ton(atField)
print(tobits32(bit32.replace(
0b_10000000_00000000_00000000_00000000,
0b_00000000_00000000_00000000_10000001,
8,8))) --> 10000000 00000000 10000001 00000000
bit32.countlz() (clz(a))
Counts ammount of zeros from left → until finds first 1
print(bit32.countlz(0b_00000000_00000000_00000000_10000000)) --> 24
print(bit32.countlz(0b_10000000_00000000_00000000_10000000)) --> 0
print(bit32.countlz(0b_00000001_00000000_00000000_00000000)) --> 7
print(bit32.countlz(0)) --> 32
bit32.countrz() (ctz(a))
Counts ammount of zeros from right ← until finds first 1
print(bit32.countrz(0b_00000001_00000000_00000000_00000000)) --> 24
print(bit32.countrz(0b_00000000_00000000_00000000_00000001)) --> 0
print(bit32.countrz(0b_00000000_00000000_00000000_10000000)) --> 7
print(bit32.countrz(0)) --> 32
That’s it for the bit32 library; that’s all the functions, lol!
buffer library
A buffer is an object that represents a fixed-size mutable block of memory.
That means once you create a buffer, its size cannot be changed.
But you are still capable of extracting data and moving it to a bigger buffer (through buffer.copy()), although it is not recommended.
Its best for you to never attempt buffer “expansion” and instead have a static, deterministic scale
Unlike bit32, where we were limited to just 4 bytes, here we can allocate up to 1 GB of memory ![]()
Although allocating a lot of memory may throw an error, that is never going to happen when you have reasonable buffer sizes from 1 KB to a few megabytes.
How to create a buffer?
Buffer has a function buffer.create() that requires you to pass the amount of bytes you want allocated; for example, if we want to store a single u32 (and as we know, 32 bits / 8 = 4 bytes), then we need to allocate 4 bytes.
Remember the number type naming convention we spoke about earlier?
Read/Write in our first buffer
Alright, let’s attempt to read and write.
We will use 2 functions:
buffer.writeu32() and buffer.readu32()
Both of these functions require you to pass:
A) Buffer
B) Offset
Offset essentially means the index of our buffer; it goes from 0 to X-1 amount of bytes we allocated.
Since we just allocated 4 bytes, aka a requirement or single u32 we should just start from offset 0.
Note that if we had the next value, the second offset would’ve been 4. Our value will be stored in [0, 1, 2, 3] bytes right now.
local buff = buffer.create(4)
buffer.writeu32(buff,0,1000)
print(buffer.readu32(buff,0)) --> 1000
BOOM! We just used our first buffer!
Other datatypes
As I mentioned, buffer can store almost everything as long as it can be encoded into bits;
It can’t store runtime stuff like instance references, but it can store data to recreate that instance 1 to 1. For example, it could store data to create Vector2, Vector3, CFrame, UDim2, and literally any other data type!
All you have to do is make an algorithm for it to interpret that data correctly.
Some data types are very straightforward, like numbers and strings, but some (like booleans) require using the bit32 library for best results.
Obviously you can just have a dummy “byte” with u8 integer outputting true/false, but that’s not efficient since we can cram 8 booleans into a single byte!
String size UTF-8 & ASCII
Strings in Luau are like buffers but are immutable; they can be any size, and *
characters can NOT ALWAYS be just 1 byte.
ASCII characters include the English alphabet and some math and other symbols.
There are a total of 128 ASCII characters.
Note that # and string.len() actually return the amount of bytes the string contains; they do not return the amount of characters, shocking to hear, maybe, and hence:
print(#"🤑") --> 4
There are function that solves it though:
print(utf8.len("🤑")) --> 1
But we will mostly not really care about it that much; we care what space string takes up.
The easiest way to check if a character is ASCII is to check if it returns 1 after a length operation:
print(#"a") --> 1 (is ASCII)
print(#"Ї") --> 2 (UTF8 cyrilic character)
Cyrillic and Greek alphabets always take up 2 bytes, by the way.
As well as SOME characters like “Æ”, “Ō”, “Ö” etc.
utf8.len could also error (not an actual script error, don’t worry).
local len,err = utf8.len("🤑")
If len == nil, then that would mean that character is invalid and err would equal a position of corrupted byte in string.
Remember: Byte length ≠ character length
UTF-8 chars can be max 4 bytes, but note that people could make corrupted strings with invalid Unicode IDs, making character display broken.
Strings may contain invalid UTF-8 byte sequences that do not form characters, basically.
When a character cannot be interpreted, it will be displayed as “�” aka invalid Unicode character.
string.byte() vs utf8.codepoint()
string.byte() is for BYTES ONLY (ideal for ASCII), and utf8.codepoint() is for UTF-8 and ASCII.
Both of them return an integer representing position in BYTES and UTF8 that can be converted back into a character using string.char() or utf8.char(), which will be super useful very soon.
Both of them support strings and not just characters
Both of them require you to pass BYTE RANGE of a string to the i and j arguments or use the default value of 1
local a,b,c,d,e = string.byte("Hello",1,5)
print(a,b,c,d,e) --> 72 101 108 108 111
local a,b,c,d,e = utf8.codepoint("Hello",1,5)
print(a,b,c,d,e) --> 72 101 108 108 111
The difference is that string.byte is strict, with no step further j argument, while utf8.codepoint() acts like an intersection and can go past j if there are bytes required to complete the latest character.
A prime example would be
print(utf8.codepoint("🤑",1,1)) --> 129297
String is 4 bytes, and the default argument is 1 but it still went out of its way to grab 3 more bytes!
So:
| Argument | Value |
|---|---|
| i | 1 |
| j | i (1) |
Quickly turned into:
| Argument | Value |
|---|---|
| i | 1 |
| j | 4 |
In order to complete character!
| Function | Works on | Returns | Notes |
|---|---|---|---|
| string.byte | raw bytes or ASCII | integer per byte | Strict, does not complete multi-byte characters |
| utf8.codepoint | UTF-8 or ASCII | integer Unicode codepoint | Will read extra bytes to finish a character if needed, “intersection behavior” |
i & j arguments
- Both take byte positions, not character counts.
utf8.codepointwill auto-extendjto complete the last character if it’s multi-byte.
Visual mental model
string.byte("🤑", 1)→ just first byte (240)utf8.codepoint("🤑", 1)→ full codepoint (129297)
Intersection idea:
utf8.codepointreads bytes fromitoj, but can go pastjif the last character needs more bytes to form a valid codepoint.
Note: for optimization reasons leaving
iandjargument empty is preferable, their default value is 1 in both string.byte() and utf8.codepoint()
Using strings
So let’s write our string inside a table!
But as we found out, the #length operator tells us the size of the string, aka the exact amount of bytes the string would require to allocate!
local str = "Hello 👋"
local len = #str
local buff = buffer.create(len)
buffer.writestring(buff,0,str)
print(buffer.readstring(buff,0,len)) --> Hello 👋
Note: buffer.writestring has 4th parameter that lets you crop string passed into the buffer.
Storing multiple numbers
Here is a number of ranges; pick accordingly:
| Bits | Unsigned (U) | Signed (I) | Float (F) |
|---|---|---|---|
| 8 | 0 … 255 | -128 … 127 | |
| 16 | 0 … 65,535 | -32,768 … 32,767 | |
| 32 | 0 … 4,294,967,295 | -2,147,483,648 … 2,147,483,647 | 32-bit float (IEEE 754) |
| 64 | 64-bit float (double, IEEE 754) |
Picked? Good!
In our example, we will try packing an array of i32 into a buffer and then pack out!
local array = {
-4;
-99999;
4444;
2144214;
-4214124;
4248098;
}
local buff = buffer.create(#array*4)
local pos = 0
for i,v in array do
buffer.writei32(buff,pos,v)
pos+=4
end
local tab = {}-- or table.create(buffer.len(buff)/4)
local pos = 1
for i=0,buffer.len(buff)-1,4 do
tab[pos] = buffer.readi32(buff,i)
pos+=1
end
warn(tab)
Explanation:
- Why
#array*4?
A: #array = amount of slots * 4 bytes since eachi32takes 4 bytes - Why pos+=4?
A: Unlike arrays, we write into actual bytes, so we need actual spacing to the next byte sequence. - What the hell is it?
for i=0,buffer.len(buff)-1,4 do
A: That’s a very basic for loop for buffers. Unlike Luau (or Lua) tables, in buffer index starts at 1; buffer.len()-1 is needed so our iteration stops at the index of the last byte.
Think of it like this: 4 bytes is the length, but the actual index goes to 3[0, 1, 2, 3]and 4 in the for loop means it incrementsiby 4, aka perfect spacing for this buffer.
Splitting strings
Now let’s get a lot more serious about storing multiple strings with different lengths!
We can’t pack strings the same way we packed numbers since, as we know, their length is not deterministic. There are multiple ways to solve this issue. In “ancient times of programming” strings were split, usually by the \0 symbol called “string terminator.” This was pretty good at the time, but the longer the string, the more overhead it has archived. To find the last symbol, you would’ve had to iterate through all the characters to find the ending of a string, not to mention the huge vulnerability to users passing the “\0” symbol and breaking your entire program!
Solution? String ending pointer!
Have an integer that tells you the end of the string.
It all depends. If the string is shorter than 256 bytes, then you can have just 1 byte of the u8 number.
Position VS Offset.
-
Position = an actual position in buffer pointing to the end of string
Pros: Most optimized
Cons: depending on buffer range,u8would not be enough to point to a position; good if the pointer is something likeu32though. -
Offset = Start of string + x = end position
Pros: scales really well as long as you don’t reach the byte limit per string
Does not care on what byte string is positioned; it’s an offset, after all.
Cons: slightly less performant
On Roblox, though, you are forced to use “Offset” since the buffer library works on offsets.
Here is an example code: using offsets and the u8 integer as a pointer.
Meaning string is max 255 bytes
local tab = {
"Hello";
"World";
"Buffers are cool";
"Yes 🤑"
}
local len = 0
for i,v in tab do len+=#v+1 end
local buff = buffer.create(len)
--writing
local pos = 0
for i,v in tab do
local str_len = #v
buffer.writeu8(buff,pos,str_len)
local next_pos = pos+1
buffer.writestring(buff,next_pos,v)
pos = next_pos+str_len
end
--deserializing
local t = {}
local len = buffer.len(buff)
local i = 0
local pos = 1
while i<len do
local len = buffer.readu8(buff,i)
local i_ = i+1
local str = buffer.readstring(buff,i_,len)
t[pos] = str
pos+=1
i=i_+len
end
warn(t)
buffer.readstring = slow?
So we have been using strings; what about individual characters?
In that case you might want to avoid the use of string functions and instead use u8, u16 or u32 to encode numbers; it will be roughly x1.6 times faster, more optimized, and safer.
It all depends on what kind of character you are encoding.
If the character’s length is 4 bytes (emoji), you need u32 minimum; if it’s Cyrillic (2 bytes), then u16 is enough, and for ASCII, u8 is all you need.
Note that you can still use u32 for ASCII and 2-byte symbols, but that’s not very efficient unless you want to save ANY character.
Also note this is purely for a SINGLE CHARACTER; DON’T USE IT FOR STRINGS!
u8 (ASCII)
local char = buffer.create(1)
buffer.writeu8(char,0,string.byte("h"))
print(string.char(buffer.readu8(char,0))) --> h
u16 (UTF-8)
local char = buffer.create(2)
buffer.writeu16(char,0,utf8.codepoint("Ї"))
print(utf8.char(buffer.readu16(char,0))) --> Ї
u32 (UTF-8)
local char = buffer.create(4)
buffer.writeu32(char,0,utf8.codepoint("🤑"))
print(utf8.char(buffer.readu32(char,0))) --> 🤑
Booleans (bit32
buffer)
With the use of bit32, you can store up to 32 booleans in u32 and 8 booleans in u8 tax free ![]()
8 booleans in just 1 byte
bro its OP
We won’t really use buffer.writebits() or buffer.readbits() since bit32.extract() exists and does the job arguably better.
Still, I bet they have some use cases where you want to use them; just know alternatives exist.
32 booleans
local buff = buffer.create(4)
local flag = 0b_00000000_00000000_00000000_00000000
--toggling bit flags (booleans)
flag = bit32.bor(flag,0b_10000010_00001000_00000100_00001000)
buffer.writeu32(buff,0,flag)
print(tobits32(buffer.readu32(buff,0))) --> 10000010 00001000 00000100 00001000
16 booleans
local buff = buffer.create(2)
local flag = 0b_00000000_00000000
--toggling bit flags (booleans)
flag = bit32.bor(flag,0b_00000100_00001000)
buffer.writeu16(buff,0,flag)
print(tobits32(buffer.readu16(buff,0))) --> 00000100 00001000
8 booleans
local buff = buffer.create(1)
local flag = 0b_00000000
--toggling bit flags (booleans)
flag = bit32.bor(flag,0b_10100100)
buffer.writeu8(buff,0,flag)
local res = buffer.readu8(buff,0)
print(tobits32(res)) --> 10100100
local bool1 = bit32.btest(res,0b_00000001)
local bool2 = bit32.btest(res,0b_00000010)
local bool3 = bit32.btest(res,0b_00000100)
local bool4 = bit32.btest(res,0b_00001000)
local bool5 = bit32.btest(res,0b_00010000)
local bool6 = bit32.btest(res,0b_00100000)
local bool7 = bit32.btest(res,0b_01000000)
local bool8 = bit32.btest(res,0b_10000000)
print(bool8,bool7,bool6,bool5,bool4,bool3,bool2,bool1) --> true false true false false true false false
Schemas
Ok, assume we have a mixed buffer.
And we have to navigate it somehow?
Player settings, etc., could contain pretty much any data.
For that purpose we can make a sort of “blueprint” that is usually referred to as a schema!
There are 2 types of schemas as well: internal and external. Internals are integrated inside the buffer directly and work very similarly to “string end pointers”
External ones are usually safer and easier, so we will use them. They are usually implemented through arrays and are meant for rigid buffers, “configurators” but may work for other kinds with repeatable patterns.
External schema:
local schema = {
[1] = "string";
[2] = "i8";
[3] = "f64";
}
-- theoretical buffer
local buff = buffer.create(15)
buffer.writeu8(buff,0,5)
buffer.writestring(buff,1,"Hello")
buffer.writei8(buff,6,-120)
buffer.writef64(buff,7,8888888888)
local tab = {}
local tabL_pos = 1
local buff_index = 0
for i,v in schema do
if v =="string" then
local len = buffer.readu8(buff,buff_index)
local _i = buff_index+1
local str = buffer.readstring(buff,_i,len)
tab[tabL_pos] = str
tabL_pos+=1
buff_index=_i+len
elseif v=="i8" then
local i8 = buffer.readi8(buff,buff_index)
tab[tabL_pos] = i8
tabL_pos+=1
buff_index+=1
elseif v=="f64" then
local f64 = buffer.readf64(buff,buff_index)
tab[tabL_pos] = f64
tabL_pos+=1
buff_index+=8
end
end
warn(tab)
Internal schema:
local Interpretation_Sheet = {
[1] = "string";
[2] = "char";--u32 utf8 char in our case, you can make u8 and u16 aswell
[3] = "u8";
[4] = "f32";
-- treat rest as undefined and break loop then
}
-- internal schema
local buff = buffer.create(20)
buffer.writeu8(buff,0,1)--type pointer
buffer.writeu8(buff,1,5)--string end pointer (u8),255 byte limit per string in this case
buffer.writestring(buff,2,"Hello")--string itself
buffer.writeu8(buff,7,2)--type pointer
buffer.writeu32(buff,8,utf8.codepoint("😂"))--4 byte char
buffer.writeu8(buff,12,3)--type pointer
buffer.writeu8(buff,13,255)-- u8
buffer.writeu8(buff,14,4)--type pointer
buffer.writef32(buff,15,0.05)-- f32
local tab = {}
local tab_pos = 1
local i = 0
while i<buffer.len(buff)-1 do
local type = Interpretation_Sheet[buffer.readu8(buff,i)]
if not type then break end
local _i = i+1
if type =="string" then
local len = buffer.readu8(buff,_i)
local _i = _i+1
local str = buffer.readstring(buff,_i,len)
tab[tab_pos]=str
tab_pos+=1
i=_i+len
elseif type=="char" then
local char = utf8.char(buffer.readu32(buff,_i))
tab[tab_pos]=char
tab_pos+=1
i=_i+4
elseif type=="u8" then
local u8 = buffer.readu8(buff,_i)
tab[tab_pos]=u8
tab_pos+=1
i=_i+1
elseif type=="f32" then
local f32 = buffer.readf32(buff,_i)
tab[tab_pos]=f32
tab_pos+=1
i=_i+4
end
end
warn(tab)
Evil64
(works for up to 52-bit integers, actually)
You can use actual arithmetic to manipulate bits!
Unlike bit32, this way you gain access to the whole 64-bit float!
Due to the fact that Luau is structured this way, it will be faster than the bit32 library, but ONLY if you have not set –!native compilation mode and only in some cases.
Note that F64 (the one we will work with) has entirely different architecture IEEE-754
Visualization function:
--Visualize F64 IEEE-754
local function tobits64(x:number):string
if x == 0 then
return "0 " .. string.rep("0", 11) .. " " .. string.rep("0", 52)
end
local sign = x < 0 and 1 or 0
x = math.abs(x)
-- decompose
local m, e = math.frexp(x)
-- normalize mantissa to [1,2)
m = m * 2
e = e - 1
-- IEEE-754 exponent bias
local exp = e + 1023
-- build exponent bits
local expBits = ""
for i = 10, 0, -1 do
expBits ..= (math.floor(exp / 2^i) % 2)
end
-- remove implicit leading 1
m = m - 1
-- build mantissa bits
local manBits = ""
for i = 1, 52 do
m = m * 2
if m >= 1 then
manBits ..= "1"
m = m - 1
else
manBits ..= "0"
end
end
return sign .. " " .. expBits .. " " .. manBits
end
Now here are 6 absolutely illegal (not really) functions:
--Bit at <strong>k</strong> position is true?
local function hasBit(n:number, k:number):boolean
return math.floor(n / 2^k) % 2 == 1
end
--Forces bit at <strong>k</strong> position to be true
local function setBit(n:number,k:number):number
if hasBit(n, k) then
return n
end
return n + 2^k
end
--Forces bit at <strong>k</strong> position to be false
local function clearBit(n:number, k:number):number
if not hasBit(n, k) then
return n
end
return n - 2^k
end
--Equalent of bit32.extract
local function extractBits(n:number, from:number, count:number):number
return (n / 2^from)//1 % 2^count
end
--Flips bit state at <strong>k</strong> position
local function toggleBit(n:number, k:number):number
return hasBit(n, k) and (n - 2^k) or (n + 2^k)
end
--Visualize 52-bit range
local function tobits52(n:number):string
local s = ""
for k = 52, 0, -1 do
s ..= hasBit(n, k) and "1" or "0"
if k % 8 == 0 then s ..= "\t" end
end
return s
end
It’s basically bit32.band() and bit32.bor() but more cursed and powerful ![]()
You may use the tobits64 function to visualize them too, but it outputs results in IEEE-754 so you will likely understand nothing.
You can keep using the tobits32 or tobits52 function for visualization.
This function requires you to pass a number as the 1st argument and a bit index as the 2nd argument.
print(tobits32(setBit(0,7))) --> 00000000 00000000 00000000 10000000
True power:
local n = setBit(0,52)
print(hasBit(n,52)) --> true
n = clearBit(n,52)
print(hasBit(n,52)) --> false
local n = 0b_00000000_10000100_00000000
print(tobits32(extractBits(n,8,8))) --> 10000100
local n = 0b_00000001
n = toggleBit(n,0)
print(tobits32(n)) --> 00000000
n = toggleBit(n,0)
print(tobits32(n)) --> 00000001
You can pack 52 booleans into only 1 number
bit32 could only dream of that!
You can pack even more than 52 bits as well, but it’s a sketchy area; things will start to break.
String packs
String packs are an ancient-era buffer; they existed almost forever but are not very relevant today. It’s good to know them if you need to translate legacy Lua/Luau code to a modern buffer library.
The format can be found here:
https://www.lua.org/manual/5.3/manual.html#6.4.2
Use of them consists of string.pack(), string.unpack() and string.packsize()
string.pack(fmt, …)
- Packs values into a binary string according to a format string.
b→ signed 8-bit integerB→ unsigned 8-bit integerh→ signed 16-bit integerH→ unsigned 16-bit integeri→ signed 32-bit integerI→ unsigned 32-bit integerf→ float (32-bit)d→ double (64-bit)
- Returns a string of raw bytes, perfectly packed.
local packed = string.pack("BBH", 10, 255, 500)
print(#packed) --> 4 bytes: 1+1+2
string.unpack(fmt, s, pos)
- Reads back the values from a packed string.
readStartis optional (start index in string).- Returns all unpacked values + next read index.
local s = string.pack("BBH", 10, 255, 500)
local a,b,c,nextPos = string.unpack("BBH", s)
print(a,b,c,nextPos) --> 10 255 500 5
nextPos is where the next unpack would start.
Lowercase = signed (i)
Uppercase = unsigned (u)
| Metric | Size |
|---|---|
| Char | 1 byte |
| Short | 2 bytes |
| Float | 4 bytes |
| Double | 8 bytes |
Anything marked “native” depends on the platform.
If you care about layout, use i[n] / I[n].
E.g.:
i[4] = i32
I[4] = u32
string.packsize(fmt)
- Returns how many bytes a given format string will occupy.
print(string.packsize("BBH")) --> 4
print(string.packsize("iI")) --> 8
Conclusion
Buffers are not data.
Buffers are storage.
Meaning does not live inside memory.
Meaning lives in:
- Your schema
- Your offsets
- Your interpretation rules
If two programs agree on layout, they can talk.
If they don’t, the buffer is just noise.
Rules you should not break
- Bytes are the law
- Everything is offsets and sizes
- Characters, numbers, and booleans are interpretations
- Layout before code
- Design the memory map first
- Then write read/write logic
- Deterministic size wins
- Fixed-size buffers > dynamic growth
- Predictability beats convenience
- Schemas are contracts
- External schema = safer
- Internal schema = denser
- Version them or suffer later
- UTF-8 is hostile
- Byte length ≠ character count
- Never assume 1 char = 1 byte
Note that you should be extra careful with user-passed buffers; string length could be out of bounds, etc., or invalid interpretation.
When should you actually use buffers?
Use buffers when:
- Networking
- Data Stores
- Save files
- Compression
- Replication
- Deterministic serialization
Final takeaway
If you understand this post, you now understand:
- How memory works
- How serialization works
- How engines move data
You’re no longer “using APIs”.
You’re designing data.
That’s the line between:
scripting
and
systems programming
Footer
© 2025 The New Luau Order Certified Learning and Education Program™
Happy 25th of December - go touch snow or something










