Save-Point
Load/save cache files - Printable Version

+- Save-Point (https://www.save-point.org)
+-- Forum: Games Development (https://www.save-point.org/forum-4.html)
+--- Forum: Code Support (https://www.save-point.org/forum-20.html)
+--- Thread: Load/save cache files (/thread-2907.html)



Load/save cache files - DerVVulfman - 04-03-2009

Before I show you the routines that save and load data, let me just give you an example of the data to be saved or loaded:

Code:
class Game_File
  attr_accessor :a_record
  def initialize
    a_record = "This is a score"
  end
end
$game_file = Game_File.new
This routine creates an 'object' or class called Game_File. It has only 1 value that I call 'a_record' and once I initialize it, I have it set up with 'This is a score' as a default. After that, I attach this object/class to a global value called $game_file.

This is how they make $game_system, $game_temp, and all those others you access throughout the system.

* * *

Now, I'll show you a simple system you can use to save data.

Code:
file = File.open(filename, "wb")
  Marshal.dump($game_file, file)
file.close
  • This system merely opens a file... assigning a value to the 'file' value. The 'wb' means write in binary.
  • It then performs the 'Marshal.dump' which takes the data from your $game_file value and records it in Ruby's binary language.
  • Then it finally closes your file.
Simple.

* * *


Finally, the way to load your data.

Code:
file = File.open(filename, "rb")
  $game_file = Marshal.load(file)
file.close
  • This system merely opens a file... assigning a value to the 'file' value. The 'rb' means read in binary.
  • It then performs the 'Marshal.load' which gets your data from a file and stores it in the $game_file global value.
  • Then it finally closes your file.
Done