lua-users home
lua-l archive

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

Maybe a middle road that is useful for all cases, if not as consistent and simple as I would like: Obviously one would normally expect the end index to be equal or greater than the start index. If it is not, i.e. if the end index is smaller than the start index, then it can be treated the same as string.sub would, e.g. an index relative to the end. If the end index is equal or greater than the start index, then it is always treated as an actual index even if it's a negative one.

This still doesn't cover all possible cases, e.g. unpack(tab, -3, -2) where the end index is meant as counting back relative to the end rather than an actual index. And maybe it would still be too confusing, I don't know I'm just thinking out loud :-D

From: Rici Lake <>
Reply-To: Lua list <>
To: Lua list <>
Subject: Behaviour of unpack in 5.1alpha
Date: Tue, 18 Oct 2005 10:59:41 -0500

The 5.1alpha version of unpack allows you to specify start and end indices, which is useful.

There is an undocumented feature where:
  unpack(tab, start, -1)
is the same as
  unpack(tab, start, #tab)

Any other negative index is treated as a negative index. Unfortunately, this creates an inconsistency; if the table actually has negative indices (say, the arg table in the standalone interpreter), then:
  unpack(arg, -3, -2) -- works as expected
  unpack(arg, -3, -1) -- does not work as expected
(As always, depending on one's expectations)

In any event, unpack(tab, start, -fin) is not equivalent to unpack(tab, start, #tab+1-fin), as one might expect by analogy with string.sub, unless -fin is exactly -1.

I think its behaviour ought to be consistent. Either negative indices are always valid and treated literally as negative indices, or both negative start and negative fin are treated as relative to #tab (which would make it useless for arrays which actually had negative indices).