lua-users home
lua-l archive

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

On Sat, Sep 1, 2018 at 1:09 AM, Albert Chan wrote:
> But it appears that math.huge as argument also raises this error.
> IMO, the following use cases should be considered as being valid:
>    string.sub("abc", 2, math.huge)
>    string.sub("abc", -math.huge, -2)
> Yes, I know we could use -1 and 1 values respectively to get the same results,
> but infinite values are suitable for the semantic of the function.

I just felt uneasy using infinity as end-point ...
Especially bad if the infinity value is hidden behind a variable.

What is gain by not using 1 for first location, -1 for last ?

local function get_suffix_of_length(str, len)
   return str:sub(-len)

get_suffix_of_length(s, math.huge)  -- Easily understandable
get_suffix_of_length(s, -1)  -- What does "the suffix of length (-1)" mean?

So, the gain is readability.
We have expected behavior for the case when variable suffix_length = math.huge
We don't need to introduce magic number in a documentation: "(-1) means maximal length"
Infinity is very natural value, every user is aware of its meaning.