Posted by Velasco on Wed, 15 Sep 2010 21:02:56
I want to master the challenge of coding addons for WoW, although I am fairly new to coding in general. I got myself a copy of the second edition of your book. So far I understood the most things (still have to flip back and forth a bit^^), but currently I am stuck at page 94 at "String Utility Function" There an example is shown how to print the length of a string.
>str="This is a string" >print(string.len(str)) 16 >print(str:len()) 16
I tested both and they work, however while I can comprehend the first example the second one is confusing me because of how the len() function is attached to the str variable. As far as I understand the colon is only a syntactic sugar to avoid writing the self argument to a function, where self is referencing to the object the function is attached to.
so when reading str:len() it's also possible to read str.len(str). If so, then how is it possible that I get a valid result, when the variable str does not contain a table object, but is actually a string?
I couldn't find anything in the LUA reference manual for 5.1 which could give me a hint why this works.
I hope somebody can direct me into the right way. Much appreciated! :)
Posted by jnwhiteh on Thu, 16 Sep 2010 08:37:27
In Lua 5.1, all strings have a metatable that enables this to happen. Specifically, the metatable is set to the 'string' table in the global environment. This means that any of the functions from the strings library, including string.len can be accessed using method notation on strings.
It's true that normally only tables can be called like this, but in reality any object with a metatable can be. There are just a limited number of objects that can have metatables. In this case, ALL strings share the same metatable.
Posted by Velasco on Fri, 17 Sep 2010 14:37:17
Thanks for the clarification :)
So, am I correct by saying that metatable functionality has been extended to objects other than tables in Lua 5.1? If so, I suspect they are explained in detail in the second edition of Programming in Lua?
Posted by jnwhiteh on Fri, 17 Sep 2010 14:47:41
I believe the change to strings gaining a metatable is detailed in the reference manual, available freely online. You set the metatable of numbers and strings using the debug.setmetatable() function.