0

I'm trying to learn metatables in Lua and I came across the following example: -

local my_metatable = {}

local my_tab = {}

setmetatable(my_tab, my_metatable)

-- Set the __index metamethod:
my_metatable.__index = function (tab, key)
    print("Hello, " .. key)
    return "cruel world"
end

-- Trigger the __index metamethod:
print("Goodbye, " .. my_tab["world"])

The result is:-

Hello, world
Goodbye, cruel world

My question is - what does the variable tab do, in my_metatable.__index = function (tab, key). I can change it to anything and it doesn't affect the program in any way.

Thanks!

;^) Zalokin

Zalokin
  • 55
  • 6
  • 1
    You can't learn if whenever you encounter any difficulty you don't Google for it yourself and lazily ask it on StackOverflow. Also on all question you have your name right under it so a signature is unnecessary. – user202729 Oct 27 '17 at 15:01
  • 1
    You can use the same metamethod (or the same metatable) for several tables The variable `tab` will be equal to the table which is being indexed. – Egor Skriptunoff Oct 27 '17 at 15:02
  • 1
    it is actually explained in the Lua manual. Would you please just refer to it befor asking questions here? Thank you.(that's the only way you'll ever learn to program on your own) – Piglet Oct 27 '17 at 16:52

1 Answers1

0

The tab parameter is passed an argument of the table itself.

For example, given your code my_tab["world"], the parameters tab and key will be passed the arguments my_tab and "world" respectively. Because you didn't use the table in your __index function, it didn't affect anything.

Here is a basic example of what it might be used for. Let us consider a special Array table that acts like an array but has some additional information:

Array = {
    length = 0,
    array = {}
}

mt = {
    __index = function(tab, index)
        return tab.array[index]
    end
}

setmetatable(t, mt)

--now when Array[3] is written, what will actually be returned is Array.array[3]

print(Array[3]) --will actually print Array.array[3]

This isn't actually the best way to implement this functionality, but hopefully this gives you an idea of why the tab parameter exists and what __index can be used for as a result.

NetherGranite
  • 1,940
  • 1
  • 14
  • 42