rawget()

The rawget() function is used to retrieve a value from a table directly, bypassing any custom behavior defined in the table's metatable. This function allows you to access the value of a key in the table without triggering the __index metamethod, which is useful for cases where you want to avoid metatable interference.

Syntax

rawget(table, key)

Parameters

  • Name
    table
    Type
    table
    Description

    The table from which the value will be retrieved.

  • Name
    key
    Type
    string|number
    Description

    The key whose value will be fetched from the table.

Return

Returns the value associated with the specified key in the table. If the key does not exist, nil is returned.

Description

rawget() provides a way to access the contents of a table without triggering any of the metatable's methods that might alter the expected behavior of the table. This is particularly useful when you want to ensure that you are retrieving the raw data stored in the table, without any additional logic being executed.

Examples

Retrieving a value in a table with rawget

local myTable = { key = "value" }
setmetatable(myTable, {
  __index = function(t, key)
    return "Value not found for key: " .. key
  end
})

local value = rawget(myTable, "key")  -- This will not trigger __index
print(value)  -- Output: value

Accessing values without triggering metatable behavior

local myData = { x = 10 }
local myMeta = {
  __index = function(t, key)
    print("Attempting to access " .. key)
    return nil
  end
}

setmetatable(myData, myMeta)

local xValue = rawget(myData, "x")  -- This will not trigger __index
print(xValue)  -- Output: 10

See also

  • setmetatable(): Sets the metatable for a table, allowing for custom behavior.
  • rawset(): Sets a value in a table without invoking the metatable's __newindex.
  • getmetatable(): Retrieves the metatable for a given table.

Was this page helpful?

Table of Contents