Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- NBT API
- -- by MysticT
- local function readShort(file)
- local r = file.read() * 256 + file.read()
- if r >= 32768 then
- r = r - 65536
- end
- return r
- end
- local function readInt(file)
- local r = 0
- for i = 1, 4 do
- r = r * 256 + file.read()
- end
- if r >= 2147483648 then
- r = r - 4294967296
- end
- return r
- end
- local function readLong(file)
- local r = 0
- for i = 1, 8 do
- r = r * 256 + file.read()
- end
- if r >= 9223372036854775808 then
- r = r - 18446744073709551616
- end
- return r
- end
- local function readFloat(file)
- for i = 1, 4 do
- file.read()
- end
- return 0
- end
- local function readDouble(file)
- for i = 1, 4 do
- file.read()
- end
- return 0
- end
- local function readByteArray(file)
- local size = readInt(file)
- local array = {}
- for i = 1, size do
- table.insert(array, file.read())
- end
- return array
- end
- local function readString(file)
- local len = readShort(file)
- local s = ""
- for i = 1, len do
- local c = file.read()
- if not c then
- break
- end
- s = s..string.char(c)
- end
- return s
- end
- local function readIntArray(file)
- local size = readInt(file)
- local array = {}
- for i = 1, size do
- table.insert(array, readInt(file))
- end
- return array
- end
- local function readTags(file)
- local function readPayload(id)
- if id == 1 then
- -- TAG_Byte
- return file.read()
- elseif id == 2 then
- -- TAG_Short
- return readShort(file)
- elseif id == 3 then
- -- TAG_Int
- return readInt(file)
- elseif id == 4 then
- -- TAG_Long
- return readLong(file)
- elseif id == 5 then
- -- TAG_Float
- return readFloat(file)
- elseif id == 6 then
- -- TAG_Double
- return readDouble(file)
- elseif id == 7 then
- -- TAG_Byte_Array
- return readByteArray(file)
- elseif id == 8 then
- -- TAG_String
- return readString(file)
- elseif id == 9 then
- -- TAG_List
- local list = {}
- local id = file.read()
- local size = readInt(file)
- for i = 1, size do
- table.insert(list, readPayload(id))
- end
- return list
- elseif id == 10 then
- -- TAG_Compound
- return readTags(file)
- elseif id == 11 then
- -- TAG_Int_Array
- return readIntArray(file)
- end
- end
- local tags = {}
- while true do
- local tag = {}
- tag.id = file.read()
- if not tag.id then
- break
- end
- if tag.id == 0 then
- -- TAG_End
- tag.name = ""
- break
- elseif tag.id > 11 then
- return nil, "Unknown tag id: "..tostring(tag.id)
- end
- tag.name = readString(file)
- tag.payload = readPayload(tag.id)
- table.insert(tags, tag)
- end
- return tags
- end
- -- API functions
- function readNBTFile(sPath)
- local file = fs.open(sPath, "rb")
- if file then
- local tags, err = readTags(file)
- file.close()
- return tags, err
- end
- return nil, "Error opening file "..sPath
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement