lua-users home
lua-l archive

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


Shmuel Zeigerman wrote:
Isn't it strange what string.find returns when the initial search position is beyond the subject end:
  print(string.find("a", ".*", 10)) --> 2  1
[...]
So I propose that string.find return nil in this case.

(Forgot to say that the issue is related to string.match as well).

Why do I think the operation results in this example are misleading:
*  as the search is conducted in the direction of growing
   positive offsets, how can we start with 10 and end up with 2?
*  how at all can we have a match, if the search region does not
   intersect with the subject?

The patch below (naturally, proposed for Lua 5.2) appears to be
very simple:

--- lstrlib.c.orig	Fri Dec 28 17:32:24 2007
+++ lstrlib.c	Wed Apr 09 21:52:24 2008
@@ -496,8 +496,10 @@
   const char *s = luaL_checklstring(L, 1, &l1);
   const char *p = luaL_checklstring(L, 2, &l2);
   ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
-  if (init < 0) init = 0;
-  else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
+  if (init < 0 || (size_t)(init) > l1) {
+    lua_pushnil(L);
+    return 1;
+  }
   if (find && (lua_toboolean(L, 4) ||  /* explicit request? */
       strpbrk(p, SPECIALS) == NULL)) {  /* or no special characters? */
     /* do a plain search */

--
Shmuel