I am creating a game with a queue system, I have created a module that stores the queue number of the players. So I decide to write it using a buffer
local USER_ID_SIZE = 4 -- 4 bytes
local Module = {}
Module.buffer = buffer.create(112)
Module.MaxOffset = 0
function Module.Write(UserId: number?, position: number?, offset: number?)
local offset = offset or USER_ID_SIZE * (position - 1)
if UserId then
Module.MaxOffset = math.max(Module.MaxOffset, offset)
buffer.writeu32(Module.buffer, offset, UserId)
else
for i = offset, Module.MaxOffset, USER_ID_SIZE do
Module.Write(Module.Read(i+USER_ID_SIZE), nil, i)
end
Module.MaxOffset = math.max(Module.MaxOffset - USER_ID_SIZE, 0)
end
end
function Module.Read(position: number): number
local offset = USER_ID_SIZE * (position - 1)
return buffer.readu32(Module.buffer, offset)
end
function Module.IsFree(position: number): boolean
return Module.Read(position) == 0
end
return Module
I belive you cannot write the same buffer position more than 1 time.
Seeing this it’s probably shifting because you cannot write a nil value in a buffer.
The problem I see it’s in the else, the position cannot be nil because you are substracting one from the position on the first place and you cannot multiply a number for a nil value.
The rest of the code doesen’t seem off place, I would consider changing the write part where you call the nil value.
I would recommend not using buffers at all unless you really need to optimize memory usage. It’ll just make things more complicated than it needs to be with no real benefit.
You can, it will just overwrite whatever bits are stored at that position
The nil aspect is weird though, this line
for i = offset, Module.MaxOffset, USER_ID_SIZE do
Module.Write(Module.Read(i+USER_ID_SIZE), nil, i)
end
Should cause an error since it will try to do nil - 1 on the first line of the Write function. I don’t know why OP is not getting an error
I don’t understand what is wrong. When you set 2 to nil, the value at position 3 is moved to position 2, as seen by print(buf.Read(2)) -- 333, which is typical behavior for queues (and how table.remove() does it)
By “the value under position 3”, do you mean like position 1 would move to position 3?
You might be able to use buffer.copy to move the whole upper values of the buffer down by UDER_ID_SIZE rather than doing it one value at a time. However I have not tested buffer.copy where the target and the source are the same buffer, and if that causes some edge case