rawset()
The rawset()
function is used to set a value in a table directly, bypassing any custom behavior defined in the table's metatable. This function allows you to manipulate the table without triggering the __newindex
metamethod, which is useful for cases where you want to avoid metatable interference.
Syntax
rawset(table, key, value)
Parameters
- Name
table
- Type
- table
- Description
The table in which the value will be set.
- Name
key
- Type
- string|number
- Description
The key under which the value will be stored in the table.
- Name
value
- Type
- any
- Description
The value to be set in the table.
Return
Returns the value that was set.
Description
rawset()
allows you to modify the contents of a table without triggering any of the metatable's methods that may alter the expected behavior of the table. This is particularly useful in scenarios where you want to maintain certain values without being affected by any overridden behaviors specified in the metatable.
Examples
Setting a value in a table with rawset
local myTable = {}
setmetatable(myTable, {
__newindex = function(t, key, value)
print("Attempting to set " .. key .. " to " .. value)
end
})
rawset(myTable, "key", "value") -- This will not trigger __newindex
print(myTable.key) -- Output: value
Modifying values without triggering metatable behavior
local myData = { x = 10 }
local myMeta = {
__newindex = function(t, key, value)
print("You cannot change " .. key)
end
}
setmetatable(myData, myMeta)
rawset(myData, "x", 20) -- This will not trigger __newindex
print(myData.x) -- Output: 20
See also
setmetatable()
: Sets the metatable for a table, allowing for custom behavior.rawget()
: Retrieves a value from a table without invoking the metatable's__index
.getmetatable()
: Retrieves the metatable for a given table.