# The __index metamethod in Lua Programming

LuaServer Side ProgrammingProgramming

Whenever we try to access a field that hasn’t been declared in a table in Lua, the answer we get is nil. While this is true, but the reason for it is that when such access happens, the interpreter triggers a search for an __index metamethod and if it doesn’t find any method named __index, then we get nil as an answer; else we will get whatever the value of the field is set in the __index metamethod.

We can explicitly put in the __index method in a table and provide it the named values that we want it to return instead of nil.

## Example

Let’s consider an example. We will create several tables describing windows. Each table will describe several parameters like size, height, width of the window; and we will also have a default constructor to create a table which is initially empty and all the fields are not-set.

Live Demo

Window = {}
Window.prototype = {x=0, y=0, width=50, height=70, }
Window.mt = {}
function Window.new (o)
setmetatable(o, Window.mt)
return o
end
w = Window.new{x=10, y=20}
print(w.x)
print(w.width)
print(w.height)

In the above example, we are trying to print the value of three different fields of the Window, the x, the width, and the height. We know that when we create a new object using the constructor, we pass the value of x, so x will not be nil, but since we didn’t tell Lua about the values of the width and height of the window object w, we will get nil.

## Output

10
nil
nil

Now, we can explicitly create a __index method in the above code to tell the interpreter that we need it to return our value instead of nil, in case it doesn’t find the field in the table.

## Example

Consider the example shown below −

Live Demo

Window = {}
Window.prototype = {x=0, y=0, width=50, height=70, }
Window.mt = {}
function Window.new (o)
setmetatable(o, Window.mt)
return o
end
Window.mt.__index = function (table, key)
return Window.prototype[key]
end
w = Window.new{x=10, y=20}
print(w.x)
print(w.width)
print(w.height)

## Output

10
50
70
Published on 19-Jul-2021 11:18:27