pg daszzz
pg daszzz

Reputation: 67

How does lua know that the __index function's second parameter is the key?

I find that lua'a object orient system and metatable very confusing, it makes simple class and instance grammar more complex than that of the C++. I was looking at this code (for this example https://www.runoob.com/lua/lua-metatables.html)

mytable = setmetatable({key1 = "value1"}, {
  __index = function(mytable, key)
    if key == "key2" then
      return "metatablevalue"
    else
      return nil
    end
  end
})

print(mytable.key1,mytable.key2)

In line2, the __index metamethod points to a function with two parameters, first is mytable(itsefl), second is key. So when the last line of print try to find key2 in mytable, mytables starts looking at the nameless metatable. However, I don't know why the second parameter is bind the input passing key. It can't be because the paramter's name is key so lua is so smart to understand that that parameter is for key because it spells k-e-y. I don't think key is a keyword in lua. Is there any hidden conventions about this naming or this __index=function(arg1,arg2) stuff?

Upvotes: 1

Views: 297

Answers (2)

koyaanisqatsi
koyaanisqatsi

Reputation: 2823

Check out if unsure with print(...)

lua_debug> test = setmetatable({}, {__index = function(...) print(...) return({...}) end})
lua_debug> print(test.hello) -- Triggering __index
table: 0x02a0a6549db0 hello -- print(...) gives out the table object and key
table: 0x02a0a65a99b0 -- The return of the __index Metatmethod Function

Upvotes: 1

ESkri
ESkri

Reputation: 1928

mytable and key are just parameter names (as in usual Lua function), you can rename them if you wish.

  __index = function(t, k)
    if k == "key2" then
      return "metatablevalue"
    else
      return nil
    end

why the second parameter is bind the input passing key.

It is by definition of the metamethod.
When __index metamethod is invoked, Lua passes two arguments in the following order:
arg#1 = an object to be indexed,
arg#2 = an index.

Upvotes: 2

Related Questions