23

I have the following code:

text = "sometext"
print( string.sub(text, ( #text - 1 )) )

I want delete the last character in text.

user3499641
  • 375
  • 2
  • 3
  • 9

2 Answers2

35

You can do like this:

text = "sometext" <-- our string
text = text:sub(1, -2)
print(text) <-- gives "sometex"

For ❤✱♔" this i did like this way

function deleteLastCharacter(str)
return(str:gsub("[%z\1-\127\194-\244][\128-\191]*$", ""))
end

for _, str in pairs{"❤✱♔" }do
print( deleteLastCharacter(str))
end
ORGL23
  • 434
  • 5
  • 10
  • 1
    @Deduplicator is asking about Unicode combining characters. They are required to follow a non-combining character. So, armed with a list of combining characters, you could backtrack. Or use a library like ICU. – Tom Blodget Jul 18 '14 at 00:17
14
text = text:sub(1, -2)

The index -2 in string.sub means the second character from the last.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294