Metatables and the __index metamethod

We have the normal table: a data structure which can hold anything that isn’t nil, the only thing you can do with it is index it, but MetaTables bring power to tables with MetaMethods, most common being __index. In this post, we will learn how to index something that doesn’t exist, and return a value.

First, let us construct a table:

local myTable = {"String", false, 50}

Next, we have to set a metatable, using the function “setmetatable()”,

setmetatable(myTable, {


}) -- {} being the metaTable

We have set the metatable, now how do we make it so when you index something that doesn’t exist, return a message or value? Well, we have to set __index as a function like this:

__index = function(table, index)
    
end

Great! We have set the the function that when you index something that doesn’t exist, return a value.
Now, let’s return a value like this!

warn("Nothing at index"..index..".")
return 0;

“return 0;” returns 0 when you index nil.
This will return 0 when we index something that doesn’t exist, now let’s see what happens.

local myTable = {"String", false, 50}

setmetatable(myTable, {

    __index = function(table, index)
        warn("Nothing at index"..index.."."
        return 0;
    end

})

local Index = myTable[5] --returns 0 and warns Nothing at index 5.

This is the __index metamethod. Hope you learnt something!

13 Likes

This could be very useful for intermediate scripters. Good job!

4 Likes

This helped me understand the __index part of metatables.

Thank you for this tutorial. If anyone is wonder how would this be helpful in a situation, try to think of it like this.

local newtable = {"Hello","New","Cool"}

setmetatable(newtable, {
	
	__index = function(table, index)
		warn("Theres nothing to print at "..index..".")
		return "World"
	end,
})

if newtable[4] == "World" then
	print(newtable[1], newtable[4].."!")
end

It’ll print

Hello World!