Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua override # for strings

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?

like image 481
Xanx Avatar asked Jan 22 '26 15:01

Xanx


1 Answers

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.

like image 148
lhf Avatar answered Jan 24 '26 11:01

lhf