lua-users home
lua-l archive

string.sub for suffix not usable with varying length (including zero)

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


Consider this function:
local function cut( str, prelen, postlen )
 return str:sub(1,prelen)..str:sub(-postlen)
end
print( cut( "abc", 1, 1 ) ) -- "ac"
print( cut( "abc", 0, 1 ) ) -- "c"
print( cut( "abc", 1, 0 ) ) -- "aabc"
This function uses the canonical way to extract a prefix and postfix 
of a string. But I think the third result is a little bit surprising.
Seems like in Lua 5.1 it was undefined what string.sub( str, 0 ) does.
Lua 5.2 has one more paragraph describing what happens in this case.
But I think this paragraph was only added for cases like this:
 string.sub( "abc", -4 )
Currently I have to special case the above function for postlen==0.
Or I have to use positive indexes. 
 string.sub( str, #str-postlen+1 )
But this is not very pretty.
Is it possible to change this?
 Jörg

AltStyle によって変換されたページ (->オリジナル) /