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§
Sourcefn __index(&self, key: any) -> any
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 })Sourcefn __newindex(&self, key: any, value: any)
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 answerDyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".