Skip to main content

indexing

Trait indexing 

Source
pub trait indexing {
    // Provided methods
    fn __index(&self, key: any) -> any { ... }
    fn __newindex(&self, key: any, value: any) { ... }
}
Expand description

Metamethods controlling indexed access.

Provided Methods§

Source

fn __index(&self, key: any) -> any

The indexing access operation t[key]. Invoked when t is not a table or when key is not present in the table. The metavalue may be a function (called with t and key) or a table (in which the access is repeated) — the latter is the basis of inheritance in Lua.

setmetatable(child, { __index = parent })
Source

fn __newindex(&self, key: any, value: any)

The indexing assignment t[key] = value. Invoked when t is not a table or when key is not present in the table. Like __index, the metavalue may be a function or another table.

§Examples
local data = {}
local t = setmetatable({}, {
  __newindex = function(t, k, v)
    print("setting", k)
    rawset(data, k, v)     -- rawset avoids re-triggering __newindex
  end,
})
t.answer = 42    --> setting   answer

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§