Introduction
In Lua, converting a string to uppercase can be done using the string.upper()
function. This function takes a string as input and returns a new string with all the letters converted to uppercase. Here’s an example:
local str = ""hello world""
local uppercaseStr = string.upper(str)
print(uppercaseStr) -- Output: HELLO WORLD
In the code snippet above, we define a variable str
and assign it the value ““hello world””. We then use the string.upper()
function to convert str
to uppercase and store the result in a new variable uppercaseStr
. Finally, we use the print()
function to display the uppercase string.
It’s worth noting that the string.upper()
function only converts alphabetic characters to uppercase. Non-alphabetic characters, such as numbers or symbols, will remain unchanged. For example:
local str = ""123abc!@#""
local uppercaseStr = string.upper(str)
print(uppercaseStr) -- Output: 123ABC!@#
In this case, the string ““123abc!@#”” is not modified by the string.upper()
function because it contains characters that are not alphabetic.
If you want to ensure that all characters in a string are converted to uppercase, including non-alphabetic ones, you can use a loop to iterate over each character and convert it individually. Here’s an example:
local str = ""123abc!@#""
local uppercaseStr = """"
for i = 1, #str do
local char = string.sub(str, i, i)
local uppercaseChar = string.upper(char)
uppercaseStr = uppercaseStr .. uppercaseChar
end
print(uppercaseStr) -- Output: 123ABC!@#
In this code snippet, we initialize an empty string uppercaseStr
and then use a loop to iterate over each character in str
. The string.sub()
function is used to extract each character at the current index i
, and the string.upper()
function is used to convert the character to uppercase. The uppercase character is then appended to uppercaseStr
using the concatenation operator ..
. After the loop finishes, uppercaseStr
contains the desired uppercase string.
I hope you found this tutorial helpful!