Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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?

3 comments

0

What line is the error, it only shows one on here.

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.

0

Another problem? Tell me it.

2 answers

✓ Accepted answer

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))

1 comment

0

Wow. I amuse myself at what I forget to include, sometimes.

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.

1 comment

0

I tried it. I see the problem with the code, but then, Encode("ab") prints ""a"b"

This discussion is preserved as it was. New answers, comments, and votes are closed.