lua string replace / remove
-- Define the original string
local originalString = "Hello, Lua! Lua is awesome!"
-- Replace occurrences of 'Lua' with 'Python'
local replacedString = originalString:gsub('Lua', 'Python')
print(replacedString)
-- Remove occurrences of 'awesome'
local removedString = replacedString:gsub('awesome', '')
print(removedString)
Explanation:
local originalString = "Hello, Lua! Lua is awesome!"
: Initializes a string variable namedoriginalString
with the value "Hello, Lua! Lua is awesome!".local replacedString = originalString:gsub('Lua', 'Python')
: Uses thegsub
function, which stands for "global substitution", to replace all occurrences of the substring 'Lua' with 'Python' in theoriginalString
. The modified string is stored in the variablereplacedString
.print(replacedString)
: Outputs thereplacedString
to the console, displaying the result of the replacement.local removedString = replacedString:gsub('awesome', '')
: Usesgsub
again to replace all occurrences of the substring 'awesome' with an empty string (effectively removing it) in thereplacedString
. The modified string is stored in the variableremovedString
.print(removedString)
: Outputs theremovedString
to the console, displaying the result after removing the specified substring.