lua-users home
lua-l archive

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


I really start to like Lua. I am not an experienced C programmer,
But I needed some boolean operations on strings:


I recompiled Lua 5.0.2.

3 new functions have been added in lstrlib.c:

	string.andbit(str1,str2)
	string.orbit(str1,str2)
	string.xorbit(str1,str2)

These functions perform boolean operations on the respective bytes in
two strings.
The resulting string has the length of the shortest string out of
{str1,str2}.



Detail:

I did the changes using the function str_lower as template.

Here the additions to lstrlib.c:

=== new functions (inserted near function str_lower) ===

static int str_or (lua_State *L) {
/* 2004-03-31 Goetz Kluge: string.orbit(str1,str2) */
  size_t l1;
  size_t l2;
  size_t i;
  luaL_Buffer b;
  const unsigned char *s1 = luaL_checklstring(L, 1, &l1);
  const unsigned char *s2 = luaL_checklstring(L, 2, &l2);
  if (l1 < l2) l1 = l2; 
  luaL_buffinit(L, &b);
  for (i=0; i<l1; i++)
    luaL_putchar(&b,(s1[i] | s2[i]));
  luaL_pushresult(&b);
  return 1;
}

static int str_and (lua_State *L) {
/* 2004-03-31 Goetz Kluge: string.andbit(str1,str2) */
  size_t l1;
  size_t l2;
  size_t i;
  luaL_Buffer b;
  const unsigned char *s1 = luaL_checklstring(L, 1, &l1);
  const unsigned char *s2 = luaL_checklstring(L, 2, &l2);
  if (l1 < l2) l1 = l2; 
  luaL_buffinit(L, &b);
  for (i=0; i<l1; i++)
    luaL_putchar(&b,(s1[i] & s2[i]));
  luaL_pushresult(&b);
  return 1;
}

static int str_xor (lua_State *L) {
/* 2004-03-31 Goetz Kluge: string.xorbit(str1,str2) */
  size_t l1;
  size_t l2;
  size_t i;
  luaL_Buffer b;
  const unsigned char *s1 = luaL_checklstring(L, 1, &l1);
  const unsigned char *s2 = luaL_checklstring(L, 2, &l2);
  if (l1 < l2) l1 = l2; 
  luaL_buffinit(L, &b);
  for (i=0; i<l1; i++)
    luaL_putchar(&b,(s1[i] ^ s2[i]));
  luaL_pushresult(&b);
  return 1;
}

=== command list ===

static const luaL_reg strlib[] = {
  {"len", str_len},
  {"sub", str_sub},
  {"lower", str_lower},
  {"upper", str_upper},
  {"char", str_char},
  {"rep", str_rep},
  {"byte", str_byte},
  {"format", str_format},
  {"dump", str_dump},
  {"find", str_find},
  {"gfind", gfind},
  {"gsub", str_gsub},
  {"orbit", str_or}, /* Goetz */
  {"andbit", str_and}, /* Goetz */
  {"xorbit", str_xor}, /* Goetz */
  {NULL, NULL}
};



Doing the changes in the string-library may have been a bit quick&dirty.
But it helped.


Goetz Kluge
2004-03-31