Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

string.byte: How do I make an encoder function?

Asked by
Minifig77 190
10 years ago

I'm trying to make a function with the command bar that encodes characters into byte and then implements the backslash so I can copy it for use in a script. For example:

Encode("ab")

would print "\97\98"

I almost had when I figured out that doing

print("\\98")

would print "\98", but I implement that into the function, and it calls an error for an unfinished string. Here's the code I tried:

function Encode(str)  final = [[]]  sub = ""  for i = 1, string.len(str) do  sub = "\"..string.sub(str, i, i)  final = final..sub  end  print(final)  end

Is there a way to make a function that does what I want?

0
What line is the error, it only shows one on here. HexC3D 830 — 10y
0
It's a command bar script. The error is on the second line of the code block where it says "sub = "\"..string.sub.. etc, etc. Minifig77 190 — 10y
0
Another problem? Tell me it. HexC3D 830 — 10y

2 answers

Log in to vote
1
Answered by
User#2 0
10 years ago

HexC3D has already mentioned the problem, when you were doing sub = "\"..string.sub(str, i, i) you were escaping the closing quote.

\ is special as it tells the interpreter "ignore the next character's syntax, treat it as you would treat a or b."

So when you do "\" you're saying "Start a string, and in this string you have a quotation mark. Ignore the quotation mark's syntax as there's a backslash before it."

What you want is "\" which is saying "Pretend the 2nd backslash is a normal character" and when you print out "\" you get "\". With this knowledge, we know that you want to have your string become "\\"..string.sub(str, i, i).

Your next mistake was you forgot to actually call string.byte on the character you got! Where else are you going to get the bytecode of the character from?

sub = "\\"..string.byte(string.sub(str, i, i))
0
Wow. I amuse myself at what I forget to include, sometimes. Minifig77 190 — 10y
Ad
Log in to vote
2
Answered by
HexC3D 830 Moderation Voter
10 years ago
function Encode(str)  final = [[]]  sub = ""  for i = 1, string.len(str) do  sub = "\""..string.sub(str, i, i)  final = final..sub  end  print(final)  end

That should fix it, the operator suggests that the string wasn't finished so a ["] should fix it.

If this helped +1, if this answered your question check mark.

0
I tried it. I see the problem with the code, but then, Encode("ab") prints ""a"b" Minifig77 190 — 10y

Answer this question