即使我用一个参数声明了函数,Lua函数也需要两个参数

Har*_*tty 2 lua

考虑下面的Lua代码:

local util = {}

function util:foo(p)
  print (p or "p is nil")
end

util.foo("Hello World")
util.foo(nil, "Hello World")
Run Code Online (Sandbox Code Playgroud)

当我在lua控制台中运行它时,我得到以下结果:

p is nil
Hello World
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释这种行为.

编辑 我通过进行以下更改使代码正常工作:

local util = {}

function util.foo(p)
  print (p or "p is nil")
end

util.foo("Hello World")
util.foo(nil, "Hello World")
Run Code Online (Sandbox Code Playgroud)

我对Lua相当新,所以任何解释这种行为的指针/链接都将受到赞赏.

Jas*_*aat 10

http://www.lua.org/pil/16.html

当您使用:syntax声明函数时,有一个未指定的参数'self',它是函数正在处理的对象.您可以使用冒号语法调用该方法:

util:foo("Hello World")

如果使用点表示法,则将该函数作为util表中的条目引用,您必须自己传递"self".

使用冒号声明foo,这两个调用是等效的:

util:foo("Hello World")
util.foo(util, "Hello World")
Run Code Online (Sandbox Code Playgroud)

要使用点语法声明这一点,您可以这样做:

function util.foo(self, p)
  print (p or "p is nil")
end
Run Code Online (Sandbox Code Playgroud)

要么

util.foo = function(self, p)
  print (p or "p is nil")
end
Run Code Online (Sandbox Code Playgroud)