Discord
Login
Community
DARK THEME

How to Save & Reload Values from a Project’s Previous Instance?

So I can change number variables through keyboard inputs, generating a score and high score through straightforward means. Now I would like help learning how I can get MicroScript to remember & reload the high score when next I open the project. @mrLman ‘s tutorial series mentioned a ‘storage.get’ command but it either didn’t work with the current version of Microscript or the tutorial didn’t explain this type of feature as well as it could have.

If reasonable, any additional advice on “save game“ code would be immensely appreciated

———

Here is the code if you need to look at it. ‘newHighScore’ and ‘oldHighScore’ are reserved if they end up being needed.

———

init = function()
  
  score = 0
  highScore = 0
  newHighScore = 0
  oldHighScore = 0
  
end

update = function()
  
  //
  
  if keyboard.press.Q then
    score += 1
  end
  if keyboard.press.W then
    score = 0
  end
  if keyboard.press.E then
    highScore = 0
  end
    
    //
    
  if score > highScore then
    highScore = 0 + score
  end
    
end

———

To save a value: storage.set("hs",highScore)

To retrieve it: highScore=storage.get("hs")

Note#1: if the value has not been saved before then a value of 0 will be returned.

Note#2: You can use whatever name you like instead of "hs".

As practice you can also try typing directly into the console to test the storage.

> storage.set("test",123)

> storage.get("test") // should return 123

As @JimB007 says =)

Applied to your example it could look like this:

init = function()
  score = 0
  highScore=storage.get("hs")
end

update = function()
  if keyboard.press.Q then
    score += 1
  end
  if keyboard.press.W then
    score = 0
  end
  if keyboard.press.E then
    highScore = 0
    storage.set("hs",highScore)    
  end

  if score > highScore then
    highScore = score
    storage.set("hs",highScore)
  end
end

draw = function()
  screen.clear()
  screen.drawText("Score     : "+score,0,50,10,'#fff')
  screen.drawText("Highscore : "+highScore,0,65,10,'#fff')
end

Live Long and Tinker

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community