3

I'm trying to imlement my own length method for strings in Lua. I have successfully overriden len() method for string, but I have no idea how to do this for # operator.

orig_len = string.len
function my_len(s)
  print(s)
  return orig_len(s)
end

string.len = my_len
abc = 'abc'

If I call:

print(abc:len())

It outputs:

abc
3

But

print(#abc)

Outputs only '3' and that means it called original length function instead of mine. Is there a way to make # call my length function?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Xanx
  • 545
  • 1
  • 5
  • 17

2 Answers2

7

You cannot override the # operator for strings in Lua, not even with metatables: the __len metamethod does not apply to strings.

In fact, there is really no notion of overriding any operators in Lua. Lua metamethods are fallbacks: they are used when Lua cannot proceed on its own. Thus, arithmetic metamethods do not apply to numbers and the length metamethod does not apply to strings.

The situation is different for tables because they are meant to implement objects in Lua.

lhf
  • 70,581
  • 9
  • 108
  • 149
4

I'm trying to imlement my own length method for strings in Lua.

You can't do this from Lua.

You'd need to modify the Lua source, specifically the virtual machine (lvm.c) and change its handling of the opcode OP_LEN. In Lua 5.2 you'd need to change luaV_objlen to check the metamethod before getting the string's actual length:

case LUA_TSTRING: {
  tm = luaT_gettmbyobj(L, rb, TM_LEN);        // <--- add this line
  if (!ttisnil(tm))                           // <--- add this line
      break;                                  // <--- add this line
  setnvalue(ra, cast_num(tsvalue(rb)->len));
  return;
}

But this seems like operator overloading abuse, like overloading + to mean division or something.

Mud
  • 28,277
  • 11
  • 59
  • 92
  • Abuse is right. Lua strings are byte-strings not character strings. Sure, there are functions that interpret them as characters, given a locale, but the length of the string should never be seen as anything other than the number of bytes. – Tom Blodget Apr 15 '14 at 23:08
  • Well, I need to make Lua to handle utf-8 strings like native. I can make my functions for that, like `strlen` or `strsub`, but I want utf-8 handling to transparent for programmer, so I need Lua string functions to work with utf-8. – Xanx Apr 16 '14 at 14:54
  • I believe that's a feature of Lua 5.3. – Mud Apr 16 '14 at 15:15