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])
print(str())
print(-str)
print(str + "er")
print(str * 2)
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() , - .