您可能需要考虑以下内容(您可以在http://www.lua.org/cgi-bin/demo在线测试):
bar = {}
bar.name = 'test'
bar['123.com'] = function(self) print(self.name) end
bar2 = setmetatable({}, {
__index = function(t, key)
return function(...)
return bar[key](bar, ...)
end
end
})
bar2['123.com']()
-- output: test
您也可以将bar
自身更改为以类似方式运行,只是您必须在分配任何值之前执行此操作 - 例如:
bar = {}
local privatekey = {}
setmetatable(bar, {
__index = function(t, key)
local value = rawget(t, privatekey)[key]
if type(value) ~= 'function' then
return value
end
return function(...)
return value(t, ...)
end
end,
__newindex = function(t, key, value)
rawset(t, privatekey, rawget(t, privatekey) or {})
rawget(t, privatekey)[key] = value
end
})
bar.name = 'test'
bar['123.com'] = function(self) print(self.name) end
bar['123.com']()
-- output: test