Delete the last character from string

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
rready123
Prole
Posts: 7
Joined: Sat Oct 26, 2013 1:02 pm

Delete the last character from string

Post by rready123 »

Hi, I've got a textarea which allows the user to type but I can't find a way to delete the last character that the user typed when the return key is pressed. My code is:

Code: Select all

function love.keypressed(key)
	if key == "q" then
		text = text .. "q"
	elseif key == "w" then
		text = text .. "w"
	elseif key == "e" then
		text = text .. "e"
	elseif key == "r" then
		text = text .. "r"
	elseif key == "t" then
		text = text .. "t"
 	elseif key == "y" then
 		text = text .. "y"
	elseif key == "u" then
		text = text .. "u"
	elseif key == "a" then
		text = text .. "a"
	elseif key == "s" then
		text = text .. "s"
	elseif key == "d" then
		text = text .. "d"
	elseif key == "f" then
		text = text .. "f"
	elseif key == "g" then
		text = text .. "g"
	elseif key == "h" then
		text = text .. "h"
	elseif key == "j" then
		text = text .. "j"
	elseif key == "k" then
		text = text .. "k"
	elseif key == "z" then
		text = text .. "z"
	elseif key == "x" then
		text = text .. "x"
	elseif key == "c" then
		text = text .. "c"
	elseif key == "v" then
		text = text .. "v"
	elseif key == "b" then
		text = text .. "b"
	elseif key == "n" then
		text = text .. "n"
	elseif key == "m" then
		text = text .. "m"
	elseif key == "." then
		text = text .. "."
	elseif key == "p" then
		text = text .. "p"
	elseif key == "o" then
		text = text .. "o"
	elseif key == "l" then
		text = text .. "l"
	elseif key == "i" then
		text = text .. "i"
	elseif key == " " then
		text = text .. " "
	elseif key == "return" then
		text = text .. "\n"
	end 
end
I have checked to see if there is a solution for this but I coudn't find anything useful :)
User avatar
MadByte
Party member
Posts: 533
Joined: Fri May 03, 2013 6:42 pm
Location: Braunschweig, Germany

Re: Delete the last character from string

Post by MadByte »

Hey there,

you could limit the characters of a string using string.sub to get the result.

untested code

Code: Select all

local string = "Hello"

function love.keypressed( key )
  if key == "delete" or key == "backspace" then
    string = string:sub( 1, #string - 1 ) -- limits string from the first to the second last character
  end
end
btw. you should take a look into patterns / character classes to avoid this endless " if key == "a" elseif key == "b" " stuff .
using patterns you can filter keys which shouldn't added to a string like return key or escape, ctrl etc...
then all you have to do is something like

Code: Select all

function love.keypressed( key )
  if key and key:match( --[[ insert pattern here --]] ) then
    string = string..key
  end
end
Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests