Skip to content

Instantly share code, notes, and snippets.

@Reselim
Last active September 3, 2021 18:36
Show Gist options
  • Save Reselim/f22b632860d97888df258ddc033925c5 to your computer and use it in GitHub Desktop.
Save Reselim/f22b632860d97888df258ddc033925c5 to your computer and use it in GitHub Desktop.
Buffer with string.pack/string.unpack
local function createReadBuffer(data)
local index = 1
local function readRaw(byteCount)
local startIndex = index
index = index + byteCount
local endIndex = index - 1
return string.byte(data, startIndex, endIndex)
end
local function process(...)
index = select(-1, ...)
return ...
end
local function read(formatString)
return process(string.unpack(formatString, data, index))
end
return {
read = read,
readRaw = readRaw,
}
end
local function createWriteBuffer()
local chunks = {}
local function writeRaw(string)
table.insert(chunks, string)
end
local function write(...)
table.insert(chunks, string.pack(...))
end
local function finish()
return table.concat(chunks, "")
end
return {
write = write,
writeRaw = writeRaw,
finish = finish,
}
end
return {
createReadBuffer = createReadBuffer,
createWriteBuffer = createWriteBuffer,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment