Last active
September 3, 2021 18:36
-
-
Save Reselim/f22b632860d97888df258ddc033925c5 to your computer and use it in GitHub Desktop.
Buffer with string.pack/string.unpack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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