Lua中捕获调用不存在的函数。

我想创建一个简单的模拟表格,告诉我什么是试图从中调用的。

我第一次尝试是:

local function capture(table, key)
    print("call to " .. tostring(table) .. " with key " .. tostring(key))
    return key
end

function getMock()
    mock = {}
    mt = { __index = capture }
    setmetatable(mock, mt)

    return mock
end

现在调用它:

t = getMock()
t.foo

打印出我预期的内容:

call to table: 002BB188 with key foo

但试图调用:

t.foo("bar")

给出:

call to table: 002BB188 with key foo
lua: test.lua:6: attempt to call field 'foo' (a string value)

现在我有两个问题:

  1. 如何避免异常,即我做错了什么?
  2. 如何捕获方法参数(在这种情况下为“bar”)?
点赞
用户172486
用户172486

你需要从 __index 处理器中返回一个函数,而不是字符串:

local function capture(table, key, rest)
    return function(...)
               local args = {...}
               print(string.format("调用 %s 的键为 %s,参数 [1] 为 %s",
                                   tostring(table), tostring(key),
                                   tostring(args[1])))
           end
end

-- 调用 table: 0x7fef5b40e310 的键为 foo,参数 [1] 为 nil
-- 调用 table: 0x7fef5b40e310 的键为 foo,参数 [1] 为 bar

你得到了一个错误,因为它试图调用结果,但它目前是键。

2013-01-06 16:09:37