GLBasic forum

Main forum => GLBasic - en => Topic started by: Richard Rae on 2005-Nov-06

Title: Saving arrays
Post by: Richard Rae on 2005-Nov-06
How would you save an array to a file and then reload that array later.
Title: Saving arrays
Post by: Kitty Hello on 2005-Nov-07
how many dimensions?
Title: Re: Saving arrays
Post by: Robert on 2016-Apr-18
I have also this question regarding a 4 dimension array.
Title: Re: Saving arrays
Post by: Robert on 2016-Apr-18
To be more specifik. Is there any method to create files with a loop or a method to save data in another form? I have thought about save in a bitmap.

In dark basic there is a command to save an array in a file so it should be possible. 
Title: Re: Saving arrays
Post by: nabz32 on 2016-Apr-18
you mean like

Code (glbasic) Select
FOR x = 0 to bounds( 0 , data[] ) - 1

FOR y = 0 to bounds( 1 , data[] ) - 1

readbyte fileChannel ,  data[x][y]

NEXT

NEXT


?
Title: Re: Saving arrays
Post by: Ian Price on 2016-Apr-18

Yep, look up SAVEWORD, SAVEBYTE, READWORD, READBYTE etc.

Here's a quick example with a 2D array. It sets up an array. Saves the data. Clears the data from array memory. Loads the data, then displays it -

Code (glbasic) Select

// --------------------------------- //
// Project: test
// Start: Monday, April 18, 2016
// IDE Version: 12.656


// SETCURRENTDIR("Media") // go to media files

GLOBAL map%[]

DIM map[5][5]

FOR x=0 TO 4
FOR y=0 TO 4
map[x][y]=RND(9)
NEXT
NEXT

save_data()

clear_data()

load_data()

show_data()


// Save data
FUNCTION save_data:

LOCAL x%, y%

LOCAL file$="mydata.dat"

OPENFILE (1,file$,0)

FOR y=0 TO 4
FOR x=0 TO 4
  WRITEWORD 1,map[x][y]
NEXT
NEXT

CLOSEFILE 1

ENDFUNCTION


// Load data
FUNCTION load_data:

LOCAL x%, y%

LOCAL file$="mydata.dat"

LOCAL ok%=DOESFILEEXIST(file$)

IF ok

OPENFILE (1,file$,1)

  FOR y=0 TO 4
  FOR x=0 TO 4
   READWORD 1,map[x][y]
  NEXT
  NEXT

CLOSEFILE 1

ENDIF

ENDFUNCTION


// Clear data
FUNCTION clear_data:

FOR x=0 TO 4
FOR y=0 TO 4
  map[x][y]=0
NEXT
NEXT

ENDFUNCTION


// show loaded data
FUNCTION show_data:

FOR x=0 TO 4
FOR y=0 TO 4
  PRINT map[x][y],x*10,y*10
NEXT
NEXT

SHOWSCREEN

KEYWAIT

ENDFUNCTION

Title: Re: Saving arrays
Post by: kanonet on 2016-Apr-18
Actually its aso possible to MEM2SPRITE an array (not sure if only 1dim or also 4dim) and save it as image. At least if we are talking about integer arrays. If you save it as PNG, you get loseless compression.
Title: Re: Saving arrays
Post by: Robert on 2016-Apr-18
Ok thanks, its that stright forward. I haven't worked so much with files in GLB and thought it was more complicated.