lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Aug 7, 2014 at 1:47 PM, Mason Mackaman <masondeanm@aol.com> wrote:
> I think the reason I’m still confused is I’m not understanding how this works. I figured when you do str:len(), you still have to access the global ‘string’ table, because that’s what the __index metamethod is for ‘str’s metatable. In which case it would be more work. Are you saying str:len() retrieves the ‘len' function without having to get _ENV.table?


__index is a direct reference to the table itself. If you do `local t
= string`, t holds a direct reference to the table, and from now on it
doesn't matter if this table is also referenced by the `string` field
in __ENV (or __G or whatnot) when you are referencing a field in `t`.


What is happening:
str:len ->
str.len(str) ->
oops, str does not have len, so ->
getmetatable(str).__index.len(str)

At this point __index is the reference to the table that conatins the
field "len"; lua doesn't even know that it is the string module. See
for instance:


```
local meta = {
  __index = {len = function() return "not string.len" end}
}
debug.setmetatable("", meta)
str = "hi"
str:len()  --> returns "not string.len", because now __index is the
table defined above
```

-- 
NI!

() - www.asciiribbon.org
/\ - ascii ribbon campaign against html e-mail and proprietary attachments