Here is my code:
local function firstLetter(str) return string.sub(str, 1, 1) end local function lastLetter(str) return string.sub(str, -1) end local function middleLetters(str) return string.sub(str, 2, -2) end local str = "Happy Forever!" print(firstLetter(str)) print(lastLetter(str)) print(middleLetters(str))
I was wondering if there is a better/easier method to getting what I need, and if I am even doing this correctly in the first place. I hope you guys can help. Thanks!
You're doing this right. string.sub
is the right way to get pieces of a string.
As a convenience, you can use a different syntax.
Instead of string.sub(str, -1)
, you can say str:sub(-1)
.
The same goes for the other uses: string.sub(str, 1, 1)
can become str:sub(1, 1)
.
Is there a particular thing you don't like about your approach that you hope you can do better? How is this being used?