pub trait lifecycle {
// Provided methods
fn __gc(&self) { ... }
fn __close(&self, errobj: any) { ... }
fn __mode(&self) -> string { ... }
fn __metatable(&self) -> any { ... }
}Expand description
Metamethods controlling the life cycle of a value.
Provided Methods§
Sourcefn __gc(&self)
fn __gc(&self)
The finalizer: called by the garbage collector when the value is
collected, if the metatable had a __gc field when it was set.
§Examples
setmetatable({}, { __gc = function() print("collected") end })
collectgarbage() --> collectedSourcefn __close(&self, errobj: any)
fn __close(&self, errobj: any)
Called when the value, used as a to-be-closed variable
(local x <close> = ...), goes out of scope.
§Examples
do
local guard <close> = setmetatable({}, {
__close = function() print("closed") end,
})
print("inside")
end
--> inside
--> closedSourcefn __mode(&self) -> string
fn __mode(&self) -> string
A metavalue controlling how the value behaves as a weak table:
"k" for weak keys, "v" for weak values, "kv" for both.
§Examples
local cache = setmetatable({}, { __mode = "k" }) -- weak keys
cache[{}] = "value"
collectgarbage()
print(next(cache)) --> nil (the key was collected)Sourcefn __metatable(&self) -> any
fn __metatable(&self) -> any
If present, protects the metatable: getmetatable
returns this metavalue instead, and
setmetatable raises an error.
§Examples
local t = setmetatable({}, { __metatable = "locked" })
print(getmetatable(t)) --> locked
print(pcall(setmetatable, t, {})) --> false cannot change a protected metatableDyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".