Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1628
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

15条回答
  •  -上瘾入骨i
    2020-12-08 08:53

    This is accomplished in Lua by setting the __index key of a metatable.

    t = {}
    meta = {__index = function(_, idx) return function() print(idx) end end}
    setmetatable(t, meta)
    
    t.foo()
    t.bar()
    

    This code will output:

    foo
    bar
    

提交回复
热议问题