Forum

> > Off Topic > Delete last character of a string in LUA?
Forums overviewOff Topic overviewLog in to reply

English Delete last character of a string in LUA?

6 replies
To the start Previous 1 Next To the start

old Delete last character of a string in LUA?

Geez
GAME BANNED Off Offline

Quote
So, I picked up LOVE framework for LUA game programming. The problem is that I have a self-made debug console in it, and the current command is stored as I string. Now, when I press backspace I want to get rid of the last character. How do I do this? Any ideas?

old String length.

KimKat
GAME BANNED Off Offline

Quote
This will do. You could also increment f value to get entire words. I strongly suggest using s:len() as it's quite effective in determining the size of a string and from there you could do further calculations. In this case I only am returning the whole string, the length of string and the last character within that string and the same in the other one. The only difference being that I don't return the last character in the string. Hope it's useful.

Don't use s:len() use #s instead. Cred to @user Avo for refreshing my memory.
s='String';f=#s;d=',';
print(s..d..f..d..s.sub(s,f,f)) -- Result: String,6,g
print(s..d..f..d..s.sub(s,0,f-1)) -- Result: String,6,Strin

function chr_mod(s,x,y)local x,y=x or #s,y or #s;return s.sub(s,x,y)end
print(chr_mod("String")) -- Return: g
print(chr_mod("String",1,5)) -- Return: Strin

Text="Hello world!"
print(Text:sub(0,-2)) -- Result: Hello world
print(Text:sub(2,-1)) -- Result: ello world!
Wrote a function to make it easier.
edited 6×, last 09.02.14 12:43:42 am

old Re: Delete last character of a string in LUA?

Avo
User Off Offline

Quote
@user VADemon: I know, there two ways; we just presented both.
@user KimKat: There's no need to complicate it.
Quote
I strongly suggest using s:len() as it's quite effective in determining the size of a string and from there you could do further calculations.
1
f = #s
will be faster and easier(especially to remember - # is also used to get a number of values in a table). It's just my own opinion.

old Re: Delete last character of a string in LUA?

KimKat
GAME BANNED Off Offline

Quote
@user Avo: I agree with you on the #s (returns string length) I am just a bit loopy. I just came from the ER and now I'm coding, so it's not easy for me to remember all things. But you're right about #s is much better in this case.
To the start Previous 1 Next To the start
Log in to replyOff Topic overviewForums overview