While learning Lua, I borrowed some code from here to use string indexing, which is exactly this:
getmetatable("").__index = function(str, i) return string.sub(str, i, i) end
After that, I wrote a function to reverse a string as practice.
function reverse_string(str)
local s = ""
for i = string.len(str), 1, -1 do s = s .. str[i] end
return s
end
That works fine, until I change the string.len(str)
to str:len()
, then I get this error:
reverse.lua:9: bad argument #2 to 'sub' (number expected, got string)
Debugging print()'s tell me that the __index
function is being called on str:len()
, and that the i
argument is becoming the string "len". I know that str:len() works without the metatable there, but as soon as I add it this happens, why?
From Lua 5.2 Refernce Manual:String Manipulation
So, the object oriented style like
str:len()
comes from the default metamethod__index
, which you have modified.