How could I get the last character in a line in a string?

Hello. As the title says, how? For example:
"
hello!
goodbye
"
How could I get the ! in “hello”?

how you would get it is putting some “” in the !. like “hello! Goodbye”

You can use sub on it, both arguments should be the length of the string.

local str = 'hi!'
print(str:sub(str:len(), str:len())) --> !

I mean if there’s multiple lines, multiline, how do I get the last character?

Are you looking for the last character of every line, or a specific line?

I’m looking for the last character of every line. Probably should’ve been more specific.

Gotcha.

You can use string.split on it, using the line break character (\n)

local str = [[hi
multi lines!]]
local split = str:split('\n')
local lastCharacters = {}
for i,v in pairs(split) do
    lastCharacters[#lastCharacters + 1] = v:sub(v:len(), v:len())
end
print(lastCharacters) --> i, !
1 Like

You can also use:

local Split =  string.split("Helllo or your string here", "") 
print(Split[#Split])

This works with multiple lines, and is fairly simpler than the other answers. (And probably much more efficient.)

An alternative solution using gmatch:

local s = "\nhello!\
helloddd\
hellodd?\
goodbye"

local endChars = {}

for char in s:gmatch("(.)[\r\n]+") do
	table.insert(endChars, char)
end
table.insert(endChars, s:match("(.)$"))
-- Printing table contents:
for _, char in ipairs(endChars) do
	print(char)
end

!
d
?
e

This only grabs the last letter of the entire string. OP’s string is a multiline string.

1 Like