Lua 实现了一种叫做元方法的东西(documentation)
元方法是存在于表之后并触发某些操作的函数,例如索引数组、读取丢失的索引、收集数组的长度,甚至是数学运算,例如 + - * /
-- Start by creating your array, and another for demonstration purposes
local object = {}
local demo = {1, 2, 3, 4}
-- Create a your metamethods contained in a table
local metamethods = {
__index = function(self, index) return demo[index] end;
__newindex = function(self, index, value) demo[index] = value end;
}
-- Lets print out what is in the object table for demonstration
print(object[1]) -- nil
print(object[2]) -- nil
print(object[3]) -- nil
print(object[4]) -- nil
-- Use the setmetatable(table a, table b) function to set the metamethods
-- stored in 'b' to 'a'
setmetatable(object, metamethods);
-- Lets print out what is in the object table for demonstration
print(object[1]) -- 1
print(object[2]) -- 2
print(object[3]) -- 3
print(object[4]) -- 4
为什么上面的代码有效?当使用索引__index(metamethods.__index)设置元表时,如果附加表的(object)键是nil,那么它将调用指定的函数。在这种情况下,它返回演示的表,索引直接传递给它。就好像:当你做object[1]时,你实际上做的是demo[1],当然是在元方法的帮助下。
setmetatable() 的一个很酷且快速的用法是它返回您作为第一个参数(表)传递的值。如果您将 nil 传递给第一个参数,它将为您提供一个新表。
local object1 = setmetatable({}, { __index = function(self, i) return 1 end })
local object2 = setmetatable(nil, { __index = function(self, i) return 2 end })
print(object1["a"])
print(object2[321])