0Pricing
Lua Academy · Lesson

__index and __newindex

Intercept field reads and writes with __index and __newindex metamethods.

__index Recap

__index is triggered when Lua tries to read a key that doesn't exist in the table. It can be a table (prototype lookup) or a function (dynamic computation). This is the most-used metamethod in Lua — it powers inheritance, default values, and lazy initialization.

local defaults = {timeout=30, retries=3}
local config = setmetatable({timeout=60}, {__index=defaults})

print(config.timeout)   -- 60 (own value)
print(config.retries)   -- 3  (from defaults)
print(config.missing)   -- nil (not in either)

__newindex Triggered

__newindex is triggered when Lua tries to write a key that does not yet exist in the table. If the key already exists, the assignment happens directly without triggering __newindex.

local proxy = setmetatable({}, {
  __newindex = function(t, k, v)
    print("New key:", k, "=", v)
    rawset(t, k, v)  -- actually store it
  end
})

proxy.x = 10    -- New key: x = 10
proxy.x = 20    -- no trigger! x already exists
print(proxy.x)  -- 20

All lessons in this course

  1. Introduction to Metatables
  2. __index and __newindex
  3. Arithmetic Metamethods
  4. __tostring and __len
← Back to Lua Academy