Metatables

hasmetafield

Returns whether the target value has a non-nil raw metafield with the requested name.

Syntax

hasmetafield(target: any, field: string): boolean

Arguments

NameTypeDescription
targetanyValue whose metatable is inspected.
fieldstringMetafield name to check.

Returns

NameTypeDescription
hasFieldbooleantrue when the raw metafield exists and is non-nil; otherwise false.

Description

Returns whether the target value has a non-nil raw metafield with the requested name. The function does not call the metafield, does not invoke __index lookup, and does not change readonly state.

Call it with 2 parameter(s): target, field. The argument table explains which values are required and which ones only refine the behavior.

It returns hasField (boolean). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Check whether a value has a non-nil raw metafield.

local target = {}
local meta = {
    __index = {},
}

setrawmetatable(target, meta)

print(hasmetafield(target, "__index"))
print(hasmetafield(target, "__newindex"))