How to convert text into a numerical string?

Hi, I’m trying to convert a text variable into a numerical string in Sugarcube, so I can jumble up the variables in my training game, and have the user email me the jumbled up code, for me to un-jumble it and see how they did and add them to a leaderboard.

On the forums I found one suggestion to use the following code at Binary Converter

it says:
“for (c of ‘banana’) console.log(c, c.charCodeAt(0).toString(2).padStart(8, ‘0’))”

But I couldn’t make it work. doesn’t seem to even be twine code… No idea… Also wasn’t able to get any of the other code on that page to work. The people commenting seem to assume you will know what to do with scripts and html code, or how macros and stuff work. I’m just looknig for sugarcube twine code (or something I can paste into the javascript location and call, however I need to parse it a variable and get a variable back and don’t know how to do that).

So I tried other approaches - I also found I can get the first character using $text.first()

This is useful as I can then convert the character into a number using a series of 26 “if” statements, but how do I get the second character etc?

There doesn’t seem to be a $text.second() nor is there a $text.deletefirst() which would enable me to query $text.first again

Any help much appreciated!

Twine Version: 2.3.9
Story Format: Sugarcube 2.31.1

How much text are you talking about? Because simply translating text into a number, assuming you need to translated it back later, would cause a HUGE amount of bloat.

If you want the simplest way to turn an object variable into something you can easily decode, you can do:

<<set $encoded = btoa(JSON.stringify($objectVar))>>

and then you can decode that with:

<<set $objectVar = JSON.parse(atob($encoded))>>

For details on what those do, check out the MDN articles on JavaScript Object Notation (JSON) and Base64 encoding.

If you wanted to put your own spin on that, you could, but there really isn’t much point, since you’re including your encoding method with your game, which means that anyone can do the same, or even just modify the variables before your game encodes it.

Hope that helps! :grinning:

Thanks! I’ll give it a go…

I’m getting get a popup saying "Error [tw-user-script-0]: invalid or unexpected token.

Although in fairness it does produce the stringified string…

Good enough for the time being :slight_smile: - thank you very much!

I just double-checked, and the code I posted works fine.

That error message should give more information to help you track down what that error is. You can check the console window for additional details (at the bottom of the “Developer Tools” window, which can be reached by hitting F12 or CTRL+SHIFT+I in most browsers).

If you can show the code that was causing that error then we could probably figure out the problem.