Lua overrides # for strings

I am trying to create my own length method for strings in Lua. I have successfully overcome the len () method for a string, but I have no idea how to do this for the # 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) 

Only 3 is output, which means that instead of mine, the function of the original length is called. Is there a way to # make a call to my length function?

+3
source share
2 answers

I am trying to create my own length method for strings in Lua.

You cannot do this from Lua.

You will need to change the source of Lua, in particular the virtual machine (lvm.c), and change its processing of the OP_LEN operation OP_LEN . In Lua 5.2, you will need to modify luaV_objlen to check the metamethod before getting the actual string 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 it looks like the operator is overloading abuse, for example, overloading + by division, or something like that.

+4
source

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

There really is no concept of overriding any operators in Lua. Lua meta methods are fallback: they are used when Lua cannot act 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 designed to implement objects in Lua.

+7
source

Source: https://habr.com/ru/post/1202040/


All Articles