[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: string.sub for suffix not usable with varying length (including zero)
- From: Dirk Laurie <dirk.laurie@...>
- Date: Mon, 11 Feb 2013 20:29:32 +0200
2013/2/11 Richter, Jörg <Joerg.Richter@pdv-fs.de>:
>> Extending a function beyond its natural domain of definition
>> always sacrifices something.
>
> sub( str, 0, nil ) can only extend sub( str, >0, nil ) or
> sub ( str, <0, nil ).
Not both. So far I am with you: something must be sacrificed.
> Currently you have:
> (1) sub( str, i>0, nil ) returns suffix of length=#str-i+1, or the empty string, if i is too big.
> (2) sub( str, i<0, nil ) returns suffix of length=-i, or str, if i too small.
Look at single bytes in your example "abcd". (Monospace font please.)
Index -2 -1 0 1 2 3 4 5 6
Value '' '' '' 'a' 'b' 'c' 'd' '' ''
Alias -4 -3 -2 -1
For valid indices, str:sub(a,b) is simply the concatenation of the
substrings at the indicated indices. This definition stays continuous
at a=0 if str:sub(0,b)=str:sub(1,b).
This is compatible with the choice made by the Lua designers: All other
negative indices and 0 alias to 1, all other positive indices alias to 4.
Nothing aliases to an index out of the range 1 to 4.
The reason why the formula #str-i+1 does not work for i>=0 is that
str:sub(0,0) is not one byte long.
And the reason why -i does work for i<=0 if you define str:sub(0,-1)
as the empty string, is that the original definition stays continuous
at a=5 if str:sub(5,b)=str:sub(4,b). So your definition requires 0
to alias to 5. That would be interesting (for example, str:sub(-4,0)
would also be the whole string) but it is not the choice made by the
Lua designers.