[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: string:sub
- From: WU Jun <quark@...>
- Date: Sat, 06 Mar 2010 16:18:00 +0800
-1 means the last char.
0 means the position before the first char.
s="123456789"
s:sub(-3,-1) -- "789", last three chars.
s:sub(1,1) -- "1", first char to first char
s:sub(2,-2) -- "2345678", second char to the char before last one.
s:sub(1,0) -- "", nothing
If a is negative, s:sub(a, b) is the same as s:sub(a+#s+1, b).
If b is negative, s:sub(a, b) is the same as s:sub(a, b+#s+1).
It makes sense.
Python uses -1 indicating the last element in lists as well:
a=[111,222,333] # a is a list
a[-1] # last one, 333
a[-3] # 111
On 03/06/2010 08:29 AM, David Burgess wrote:
It seems to me that negative values of string.sub() are inconsistent
with not only the first parameter but also with string.find().
Examples:
>s="123456789"
>=s:sub(-1)
9
>=s:sub(1,0)
>=s:sub(1,-1)
123456789
>=s:sub(1,-2)
12345678
>=s:find("56")
5 6
>=s:sub(1,6-2)
1234
>=s:sub(-1)
9
I am boldly suggesting that the second parameter with negative indices
behave the same as the first. I guess this implies that the value 0 for
the second parameter would return the length of the string.
Maybe I have used too many similar functions in other languages but -1
meaning the last character seems intuitive to me.
Anyone else of a like view?
DB