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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With