string.char()
The string.char()
function converts numeric ASCII (or Unicode) values into their corresponding characters. It is commonly used to construct strings programmatically, perform encoding tasks, or debug character-level data.
Syntax
string.char(value1, value2, ...)
Parameters
- Name
value1, value2, ...
- Type
- number
- Description
A sequence of numeric ASCII (or Unicode) values to be converted into characters. Each value must be a valid code point (e.g., between 0 and 255 for ASCII).
Return Value
The function returns:
- A string constructed by converting the provided numeric values into their corresponding characters.
Examples
Example 1: Convert a single numeric value to a character
The function converts one ASCII value to its corresponding character.
Example 1
print(string.char(65))
-- Output: A
Example 2: Convert multiple numeric values into a string
The function combines multiple ASCII values into a string.
Example 2
print(string.char(72, 101, 108, 108, 111))
-- Output: Hello
Example 3: Use Unicode values
You can use numeric Unicode values for non-ASCII characters as long as they are valid code points.
Example 3
print(string.char(195, 169))
-- Output: é (Unicode for 'é')
Example 4: Combine with string.byte()
You can use string.char()
to reverse the effect of string.byte()
.
Example 4
local byteValues = {string.byte("Lua", 1, 3)}
local reconstructed = string.char(table.unpack(byteValues))
print(reconstructed)
-- Output: Lua
Example 5: Constructing special characters
You can construct strings with special characters using their ASCII values.
Example 5
print(string.char(33, 36, 64))
-- Output: !$@
Example 6: Handling invalid values
Invalid numeric values result in an error. Ensure the values are within the valid range.
Example 6
-- print(string.char(300))
-- Error: bad argument #1 to 'char' (value out of range)
Use Cases
- Decoding: Convert numeric representations of characters back into readable strings.
- String Construction: Dynamically build strings programmatically.
- Debugging: Analyze or reconstruct encoded string data.
See also
string.byte()
: Converts characters in a string into their numeric ASCII (or Unicode) values. This is essentially the reverse ofstring.char()
.string.format()
: Useful when combining formatted text with dynamically generated characters.string.pack()
: Packs data into a binary string, which may use characters for encoding.