How can I convert a character code to a string character in Lua?

15.4k Views Asked by At

How can I convert a character code to a string character in Lua?

E.g.

d = 48
-- this is what I want
str_d = "0"
2

There are 2 best solutions below

0
On BEST ANSWER

You are looking for string.char:

string.char (···)

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Note that numerical codes are not necessarily portable across platforms.

For your example:

local d = 48
local str_d = string.char(d) -- str_d == "0"
0
On

For ASCII characters, you can use string.char.

For UTF-8 strings, you can use utf8.char(introduced in Lua 5.3) to get a character from its code point.

print(utf8.char(48))    -- 0
print(utf8.char(29790)) -- 瑞