lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2013/2/16 Egor Skriptunoff <egor.skriptunoff@gmail.com>:

> i=0 should be interpreted as "after last symbol" for suffixes' sake
> j=0 should be interpreted as "before first symbol" for prefixes' sake
> This quirk is more desirable, all special cases: sub(-0,0), sub(-0),
> sub(1,0) becomes predictable.
>
> IMHO, sub(0) should be the same as sub(0,-1) - both should return empty string.
> I never needed sub(0,j) for prefixes.
> Can anybody give an example from real life code
> where it was more convenient having ('abcd'):sub(0,4)=='abcd' ?

I have never needed str:sub(0) or str:sub(0,j) for any reason whatsoever.
I stick to string indices in the ranges -#str to -1 or 1 to #str. Even
though str:sub has fallbacks otherwise, I don't use them. If that is
a habit, errors can easily be found this way:

local strsub = string.sub
string.sub = function(str,i,j)
   local n=#str
   j=j or n
   if not ((i>0 and i<=n) or (i<0 and i>=-n)) then
error("Bad parameter #2 to string.sub: out of range") end
   if not ((j>0 and j<=n) or (j<0 and j>=-n)) then
error("Bad parameter #3 to string.sub: out of range") end
   return strsub(str,i,j)
   end