代码之家  ›  专栏  ›  技术社区  ›  shingo.nakanishi

如何在Lua中使用方法扩展现有类型,类似于Swift扩展或JavaScript原型?

lua
  •  1
  • shingo.nakanishi  · 技术社区  · 5 月前

    在Swift中,你可以使用扩展向现有类型添加方法,在JavaScript中,你也可以使用原型来做同样的事情。我如何在Lua中实现类似的功能?

    我想给数字添加一个箝位函数。

    如果这不可能,请告诉我。

    1 回复  |  直到 5 月前
        1
  •  1
  •   Oka    5 月前

    来自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