2

I want to create a lua script which will convert text to utf8 encoded string. The problem is I am using lua version 5.2 which does not support LUAJit which are having libraries to do so. So, I need a function which will do this task for me. For example I will pass "hey this is sam this side" it should give me the utf8 encoded string like "\x68\x65\x79\x20\x74\x68\x69\x73\x20\x69\x73\x20\x73\x61\x6d\x20\x74\x68\x69\x73\x20\x73\x69\x64\x65"

The requirement is like that need to use lua only.

1
  • 4
    Just a reminder - that's not utf8 encoding, that's escaping hex values in a string literal. It has nothing to do with utf. Commented Nov 17, 2021 at 11:27

1 Answer 1

3

You can do it like this:

local str = "hey this is sam this side"
local answer = string.gsub(str,"(.)",function (x) return string.format("\\x%02X",string.byte(x)) end)
print(answer)

The answer is:

"\x68\x65\x79\x20\x74\x68\x69\x73\x20\x69\x73\x20\x73\x61\x6D\x20\x74\x68\x69\x73\x20\x73\x69\x64\x65"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.