Reputation: 928
In my game i want to have a system where a user presses a button and it gives them a base64 string that they can enter on another computer to get there save data.
var cash = 2228
var seeds = 0
var Final = 0
var encodedData
var decodedData
var decodeLoad
//Function here where user inputs encoded data and sets it as the encodedData Variable
function savedata() {
encodedData = window.btoa("['"+ cash + "'], ['" + seeds + "'], ['" + Final + "']");
}
function loaddata() {
decodedData = window.atob(encodedData);
decodeLoad = decodedData
}
When the user with this save data of 2228 cash, 0 seeds and 0 Final they will get a string that looks like this
WycyMjI4J10sIFsnMCddLCBbJzAnXQ==
when that goes through the load data function it comes out as a string formatd like an array
"['2228'], ['0'], ['0']"
I then want that string to be used as an array and then the values be put into the correct variables (First one to cash, second to seeds, third to final).
Here is a snippet to show that code block in action (You can change the first 3 variables to get different results:
var cash = 2228
var seeds = 0
var Final = 0
var encodedData
var decodedData
var decodeLoad
function savedata() {
encodedData = window.btoa("['" + cash + "'], ['" + seeds + "'], ['" + Final + "']");
}
function loaddata() {
decodedData = window.atob(encodedData);
decodeLoad = decodedData
}
savedata()
loaddata()
document.write("Encoded: " + encodedData + "<br>Decoded: " + decodedData)
So Is it possible?
Upvotes: 0
Views: 1716
Reputation: 69367
I would suggest you to use a JSON object string instead, which makes it easier to distinguish the data when encoding and decoding separate variables.
You can parse your variables in a JSON object string and turn it into base64 like this:
function savedata() {
// Encode into base64 JSON object string
encodedData = btoa('{"cash":' + cash + ',"seeds":' + seeds + ',"Final":' + Final + '}');
}
In this way, you can easily parse the encoded data using JSON.parse()
to turn it into an object, and quickly assign the values back to your variables:
function loaddata() {
// Decode the base64 JSON object string
decodedData = JSON.parse(atob(encodedData));
// Put the saved values back
cash = decodedData.cash;
seeds = decodedData.seeds;
Final = decodedData.Final;
}
Upvotes: 2