Arrays of UDT's are a bit more long winded, but not bad. Maybe some people will find this snippet helpful with that. Of course, if there is a better/faster way to do it, I'd be happy to know!
// Saving and Loading UDT Array
UseNewDefaultFonts(1)
type MyType
field1 as float
field2 as integer
field3 as integer[]
endtype
MyTypeArray1 as MyType[]
MyTypeArray2 as MyType[]
// Insert some elements into MyTypeArray1
mt as MyType
for i = 1 to 3
mt.field3.length = -1
mt.field1 = 0.5 + i
mt.field2 = i * 3
for j = 0 to 4
mt.field3.insert(random(0,1000))
next j
MyTypeArray1.insert(mt)
next i
// Save MyTypeArray1 to file
SaveMyTypeArray(MyTypeArray1, "MyTypeArray.arr")
// Read file into MyTypeArray2
LoadMyTypeArray(MyTypeArray2, "MyTypeArray.arr")
// Print MyTypeArray2 to the screen
while not GetRawKeyPressed(27)
for i = 0 to MyTypeArray2.length
print(MyTypeArray2[i].field1)
print(MyTypeArray2[i].field2)
for j = 0 to MyTypeArray2[i].field3.length
print(MyTypeArray2[i].field3[j])
next j
print("")
next i
sync()
endwhile
end
// Write MyType to a file
function WriteMyType(fileID, t as MyType)
WriteFloat(fileID, t.field1)
WriteInteger(fileID, t.field2)
WriteInteger(fileID, t.field3.length) // field3 is an array, so store the array length first
for i = 0 to t.field3.length
WriteInteger(fileID,t.field3[i])
next i
endfunction
// Read MyType from a file
function ReadMyType(fileID)
t as MyType
t.field1 = ReadFloat(fileID)
t.field2 = ReadInteger(fileID)
field3Count = ReadInteger(fileID)
for i = 0 to field3Count
t.field3.insert(ReadInteger(fileID))
next i
endfunction t
// Save an array of MyType to a file
function SaveMyTypeArray(arr as MyType[], filename$)
file = OpenToWrite(filename$)
for i = 0 to arr.length
WriteMyType(file, arr[i])
next i
CloseFile(file)
endfunction
// Read a file into an array of MyType
function LoadMyTypeArray(arr ref as MyType[], filename$)
arr.length = -1
file = OpenToRead(filename$)
repeat
mt as MyType
mt = ReadMyType(file)
if FileEOF(file) = 0 then arr.insert(mt)
until FileEOF(file)
CloseFile(file)
endfunction