lua-users home
lua-l archive

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



On 19-Oct-05, at 7:58 AM, Roberto Ierusalimschy wrote:

There is an undocumented feature where:

That is not an "undocumented feature", it is an implementation
detail :)

One person's undocumented feature is ...

It's a blemish. If unpack were going to only work with
"natural indices", then indeed the manual should say that.
But in that case it would be trivial to add the behaviour
consistent with string.sub. Counterposing Mike Pall's
patch, here's mine (typed, as usual, directly into the
email (a more efficient one might avoid calling getn twice,
and a more practical one would check for underflow on both
e and i):

--- lua-5.1-alpha/src/lbaselib.c        2005-08-26 19:36:32 +0200
+++ lua-5.1-alpha-cumulative/src/lbaselib.c  2005-10-19 15:00:26 +0200
@@ -330,7 +330,9 @@
   int e = luaL_optint(L, 3, -1);
   int n;
   luaL_checktype(L, 1, LUA_TTABLE);
-  if (e == -1)
-    e = luaL_getn(L, 1);
+  if (e < 0)
+    e = luaL_getn(L, 1) + 1 - e;
+  if (i < 0)
+    i = luaL_getn(L, 1) + 1 - i;
   n = e - i + 1;  /* number of elements */
   if (n <= 0) return 0;  /* empty range */

But when I looked at the code, thinking about doing that, I
wondered to myself "what is a natural index"

 Probably the manual should say that upack only works
for natural indices.

That is, is it wrong that unpack(arg, -2, 0) works? And
if so, isn't it a little odd that unpack(arg, -2, -1)
doesn't work?

Anyway, I think it is a problem with the luaL_* API,
and possibly the lua_tonumber API as well. Although
"bulkier", the following is more useful:

int e;
if (!luaL_optintx(L, 3, &e))
  /* No integer was provided */
  e = luaL_getn(L, 1);

I don't like return parameters either, but sometimes they can be useful. For example, the Lua API:

  int lua_tonumberx (lua_State *L, int index, lua_Number *retval);

(returning false (0) on failure and not changing *retval in that case) would make many uses of it more bulletproof.