Is it possible to overload operators for strings?

Can I add my own operators and metamethods to strings in Lua?

I want to do something like this:

local str = "test"

print(str[2]) --> "e"
print(str()) --> "TEST"
print(-str) --> "tset"
print(str + "er") --> "tester"
print(str * 2) --> "testtest"
+4
source share
1 answer

Yes, using the "secret" meta-string for strings in Lua, you can define several different operator overloads for strings.

Try using the following code:

getmetatable('').__index = function(str,i) return string.sub(str,i,i) end
getmetatable('').__call = function(str,i) return string.upper(str) end
getmetatable('').__unm = function(str,i) return string.reverse(str) end
getmetatable('').__add = function(str,i) return (str .. i) end
getmetatable('').__mul = function(str,i) return string.rep(str, i) end

local str = "test"

print(str[2]) --> "e"
print(str()) --> "TEST"
print(-str) --> "tset"
print(str + "er") --> "tester"
print(str * 2) --> "testtest"

The reason you cannot use setmetatable('',...)is because it can only be used for tables. But with the “hack” above, you can easily insert different methods into strings.

, , , .

- . , , Lua , . Lua , .

, str:sub(), str:upper() , - .

+5

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


All Articles