lua-users home
lua-l archive

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


Though var:sub(i,j) is shorter than string.sub(var,i,j), I often feel that it's still too long for this very basic operation. By assigning string.sub to the __call metamethod of string type, one would be able to say var(i,j). Would it make sense to have it in Lua 5.2 ?

My tests show that there's no performance penalty caused by this change (see the patch below). There is one thing though that this patch leaves open: error messages show arguments i,j as #2,#3:
  var{}
  bad argument #2 to 'var' (number expected, got table)

Here's the patch:

diff -urN src\lstrlib.c src2\lstrlib.c
--- src\lstrlib.c	Fri Jul 11 20:27:22 2008
+++ src2\lstrlib.c	Fri Oct 17 08:52:28 2008
@@ -843,13 +843,15 @@


 static void createmetatable (lua_State *L) {
-  lua_createtable(L, 0, 1);  /* create metatable for strings */
+  lua_createtable(L, 0, 2);  /* create metatable for strings */
   lua_pushliteral(L, "");  /* dummy string */
   lua_pushvalue(L, -2);
   lua_setmetatable(L, -2);  /* set string metatable */
   lua_pop(L, 1);  /* pop dummy string */
   lua_pushvalue(L, -2);  /* string library... */
   lua_setfield(L, -2, "__index");  /* ...is the __index metamethod */
+  lua_pushcfunction(L, str_sub);
+  lua_setfield(L, -2, "__call");
   lua_pop(L, 1);  /* pop metatable */
 }

--
Shmuel