lua-users home
lua-l archive

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


>Adding this logic to Lua would be very easy. You would simply 
>go into lvm.c and change the Arith() function to test for 
>strings if op is TM_ADD and then jump out to luaV_concat() if 
>so. This adds a bit of logic to Arith() which slows down 
>every arithmetic operation. But, at worst, this is something like:
>
>    if (op == TM_ADD &&
>            (ttype(rb) == LUA_TSTRING || ttype(rc) == LUA_TSTRING))
>        luaV_concat(...);
>
>For all ops other than ADD this adds one integer compare and 
>for ADD it adds an additional one or two integer compares. 
>Not bad for what it gives you IMHO...

On Lua 5.1-work6, you can have a quick and dirty solution by simply providing
a __add metamethod for strings:

--- lstrlib.c.orig      2005-07-20 23:56:36.000000000 -0400
+++ lstrlib.c   2005-07-20 23:58:37.000000000 -0400
@@ -770,6 +770,10 @@
   {NULL, NULL}
 };
 
+static int str_concat (lua_State *L) {
+       lua_concat(L, 2);
+       return 1;
+}
 
 static void createmetatable (lua_State *L) {
   lua_newtable(L);  /* create metatable for strings */
@@ -781,6 +785,8 @@
   lua_setfield(L, -2, "__index");  /* ...is the __index metamethod */
   lua_getfield(L, -2, "len");
   lua_setfield(L, -2, "__siz");
+  lua_pushcfunction(L, str_concat);
+  lua_setfield(L, -2, "__add");
   lua_pop(L, 1);  /* pop metatable */
 }

But I'm not considering your needs here; you probably won't accept the extra
overhead and some other drawbacks ('1' + '1' == 2, for instance) since you're
fiddling with lvm. As I said, that's just quick and dirty, but at least won't
touch your arithmetic operations if they're important (ah, tradeoffs...).

Cheers,
luis, just my $.02.

-- 
A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>