Short summary on buffers

This tutorial is mainly made for people who are confused about why they have “buffer access out of bounds” error

A lot of people who haven’t heard of buffers may confuse them with arrays, and converting this code for them to buffers would look like that:

local array = {5,4,2,1,3,5}

To:

local array = buffer.create(6)
buffer.writef64(array,0,5)
buffer.writef64(array,1,4)
buffer.writef64(array,2,2)
buffer.writef64(array,3,1)
buffer.writef64(array,4,3)
buffer.writef64(array,5,5)

This is the wrong understanding of buffers.

In buffers we allocate bytes, not slots.

A note for people who didn't use table.create

When we work with tables, there is a really useful function called table.create which can allocate the amount of slots we provided it with. Mostly used at times when we don’t create a big table instantly but rather when we generate it’s amounts during runtime. Since manually extending table size is expensive, this can provide some optimization.
That’s being said, this is the main source of the confusion between buffers and tables

Briefly speaking, unlike in tables, data in buffers doesn’t have a constant size. Here is a table:

Function Bytes required
writestring Amount of characters
writeu8 1
writei8 1
writeu16 2
writeu16 2
writei16 2
writeu32 4
writei32 4
writef32 4
writef64 8
So if we would convert the code above with this knowledge, we would get this piece of code:
local array = buffer.create(48)
buffer.writef64(array,0,5)
buffer.writef64(array,8,4)
buffer.writef64(array,16,2)
buffer.writef64(array,24,1)
buffer.writef64(array,32,3)
buffer.writef64(array,40,5)

Despite allocating whole 48 bytes, this buffer is still smaller than if we would store this data in luau table.

EDIT 1: some corrections

11 Likes