来自Lua,如果
debug
图书馆可用,您可以使用
debug.getmetatable
和
debug.setmetatable
更改
跖骨
对于非表类型。
与任何元表一样
__index
元方法可用于使对象对键索引做出响应。
一个粗略的例子。请注意,在
debug.getmetatable(0)
和
debug.setmetatable(0, mt)
,
0
是任意选择的
number
价值。通过任何
数
这些函数的值将用于访问该类型的元表。
local mt = debug.getmetatable(0) or {}
local methods = {}
mt.__index = methods
function methods:clamp(lower, upper)
if lower > self then return lower end
if upper < self then return upper end
return self
end
debug.setmetatable(0, mt)
for i = 1, 5 do
local n = math.random(100)
print(n, n:clamp(33, 66))
end
88 66
48 48
46 46
20 33
70 66
见Lua 5.4:
2.1 - Values and Types
|
2.4 â Metatables and Metamethods
|
6.10 â The Debug Library