知道是否可以调用一个值

Mar*_*ark 5 lua

请注意,此问题与纯Lua有关。我无权访问任何模块或C端。此外,我不能使用IO,操作系统或调试库。

我想做的是一个接收参数的函数:

  • 第二个数字
  • 可赎回价值

“可调用的值”是指可以调用的值。可以是:

  • 一个功能
  • 具有允许调用(通过__call元方法)的元表的表

这是可调用表的示例:

local t = {}
setmetatable(t, {
  __call = function() print("Hi.") end
})
print(type(t)) --> table
t() --> Hi.
Run Code Online (Sandbox Code Playgroud)

功能如下:

function delay(seconds, func)
  -- The second parameter is called 'func', but it can be anything that is callable.
  coroutine.wrap(function()
    wait(seconds) -- This function is defined elsewhere. It waits the ammount of time, in seconds, that it is told to.
    func() -- Calls the function/table.
  end)()
end
Run Code Online (Sandbox Code Playgroud)

但是我有一个问题。如果参数“ func”不可调用,我希望函数抛出错误。

我可以检查它是否是一个函数。但是,如果它是带有允许调用的元表的表,该怎么办?如果表的元表不受__metatable字段保护,那么我可以检查该元表是否可调用,但是否则,我将如何做呢?

请注意,我还考虑过尝试使用调用'func'参数pcall,以检查它是否可调用,但是要这样做,我需要过早调用它。

基本上,这就是问题所在:我需要知道一个函数/表是否可调用,但无需尝试调用它。

Nic*_*las 5

通常,如果元表不希望您能够获得它(通过定义__metatable为特殊的东西),那么您就不会得到它。不是来自Lua。

但是,如果您想作弊,则可以始终使用debug.getmetatable,它将返回与该对象关联的元表。


您不必过早调用pcall。观察:

pcall(function(...) return PossibleFunction(...) end, <insert arguments here>)
Run Code Online (Sandbox Code Playgroud)