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