lua-users home
lua-l archive

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

On Fri, Sep 30, 2016 at 9:42 PM, Egor Skriptunoff <> wrote:

On Thu, Sep 29, 2016 at 10:16 PM, Soni L. <> wrote:

On 29/09/16 03:26 PM, Egor Skriptunoff wrote:

IMO, "string.sub(index_from, index_to)" will be more handy if "index_from = 0'
would mean "the index after the last character"
instead of "the index before the first character".
("index_to = 0" should mean "index before the first character", as it is currently implemented in Lua)

The unexpected result of "str:sub(0)" makes programming a bit harder,
as this "feature" is actually a trap, and you are compelled
to use additional "if" to make things right.
But surprisingly, this weird logic can be beneficial in codegolf :-)

Don't you mean to say Lua should add a special-case for -0 and go against the rule of treating 0 and -0 as equal?

Negative zero is a very fragile object :-)
It can be killed accidentally by any harmless arithmetic operation.
IMO, no API should rely on negativity of zero.

I'd suggest to redefine the interpretation of zero value for "index_from" argument of string:sub.
The documentation may look like the following:

Positive indexes 1, 2, 3... count from the beginning of the string.
Negative indexes -1, -2, -3,... count backward from the end of the string.
Index 0 has special meaning, its semantic is different for "index_from" and "index_to" arguments:
index_from = 0 means "the index after the last character of the string"
index_to = 0 means "the index before the first character of the string"
In other words, the "rule of maximum restriction" holds.
There are two related Lua idioms: for any non-negative N prefix of length N is ":sub(1, N)" and suffix of length N is ":sub(-N)".

"s:sub(k,0)" and "s:sub(0,k)" are always empty strings for any s and k
Zero index always "kills" the substring.
This property is quite understandable for beginners, descriptive and memorable.