__newindex

The __newindex meta method is complementary to the __index meta method. Where __index is used to retrieve values from missing keys in a table, __newindex is used to assign values to missing keys. The __newindex method takes three arguments:

  • The table that is being operated on
  • The missing key
  • The value being assigned

Here is an example of using the __newindex meta method:

x = { }
y = { }

z = {
__index = function(table, key)
return z[key]
end,
__newindex = function(table, key, value)
z[key] = value
end
}

setmetatable(x, z)
setmetatable(y, z)

x.foo = "bar"

print (x.foo)
print (y.foo)
print (z.foo)

In this example, both tables x and y have meta table z. The z meta table has an __index meta method, which searches for a key within z whenever a nonexistent key is accessed. It also has a __newindex meta method, which sets a new key value pair in the z meta table if x or y don't have the key present already.

When executing the line x.foo = "bar", Lua sees that x does not have a foo member, but it does have a meta table with the __newindex meta method present. Lua then calls the __newindex meta method of the meta table (z), which assigns the key value pair to table z.

When printing the foo key of either table x or y, the __index meta method of their meta table, z, is invoked, returning the foo value stored in z.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.9