Lua检查方法是否存在

Dom*_*nik 3 oop lua

如何检查Lua中是否存在方法?

function Object:myMethod() end

function somewhereElse()
  local instance = Object()
  
  if instance:myMethod then 
    -- This does not work. Syntax error: Expected arguments near then.
    -- Same with type(...) or ~=nil etc. How to check colon functions?
  end
end
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

它是Lua 中的面向对象编程。检查函数或点成员(表)没有问题。但是如何检查方法( :)呢?

Pig*_*let 5

使用instance.myMethodinstance["myMethod"]

冒号语法仅允许在函数调用和函数定义中使用。

instance:myMethod()是缩写instance.myMethod(instance)

function Class:myMethod() end是缩写function Class.myMethod(self) end

function Class.myMethod(self) end是缩写Class["myMethod"] = function (self) end

也许现在很明显,方法只不过是使用方法名称作为表键存储在表字段中的函数值。

因此,与任何其他表元素一样,您只需使用键对表进行索引即可获取值。