cc-mc-server/mc/nibbleArray.lua
2024-07-12 16:58:47 +01:00

50 lines
No EOL
1.2 KiB
Lua

local util = require("util")
local bit32 = require("bit32")
local nibbleArray = {}
local defaultsTable = {
array = {}
}
function nibbleArray:new(sizeOrTable)
local newTable = util.deepCopyTable(defaultsTable) or {}
if type(sizeOrTable) == "number" then
for i = 1, sizeOrTable do
table.insert(newTable.array, 0)
end
elseif type(sizeOrTable) == "table" then
self.array = sizeOrTable
end
-- Set this table as this """class"""'s metatable
setmetatable(newTable, self)
self.__index = self
return newTable
end
function nibbleArray:get(index)
local arrayIndex = math.floor(index * 0.5)
if bit32.band(index, 1) == 0 then
return bit32.band(self.array[arrayIndex + 1], 0xf)
else
return bit32.band(bit32.rshift(self.array[arrayIndex + 1], 4), 0xf)
end
end
function nibbleArray:set(index, value)
local arrayIndex = math.floor(index * 0.5)
if bit32.band(index, 1) == 0 then
self.array[arrayIndex + 1] = bit32.bor(bit32.band(self.array[arrayIndex + 1], 0xf0), bit32.band(value, 0xf))
else
self.array[arrayIndex + 1] = bit32.bor(bit32.band(self.array[arrayIndex + 1], 0xf), bit32.rshift(bit32.band(value, 0xf), -4))
end
end
function nibbleArray:toBuffer()
return self.array
end
return nibbleArray