即使我已经用一个参数声明了函数,Lua函数也需要两个参数 [英] Lua function expects two parameters even when I have declared the function with one parameter

查看:83
本文介绍了即使我已经用一个参数声明了函数,Lua函数也需要两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Lua代码:

local util = {}

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

util.foo("Hello World")
util.foo(nil, "Hello World")

在lua控制台中运行此命令时,会得到以下结果:

When I run this in lua console, I get following result:

p is nil
Hello World

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

Can somebody explain this behavior to me.

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

Edit I got the code working by making following change:

local util = {}

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

util.foo("Hello World")
util.foo(nil, "Hello World")

我对Lua相当陌生,因此,任何解释此行为的指针/链接都将受到赞赏.

I am fairly new to Lua, so any pointers/links explaining this behavior will be appreciated.

推荐答案

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

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

When you declare the function using the : syntax there is an unspecified parameter 'self' which is the object the function is working on. You can call the method using the colon syntax:

util:foo("Hello World")

如果使用点符号,则将函数引用为util表中的条目,并且您必须自己传递"self".

If you use the dot notation, you are referencing the function as an entry in the util table and you have to pass 'self' yourself.

在用冒号声明foo的情况下,这两个调用是等效的:

With foo declared with a colon, these two calls are equivalent:

util:foo("Hello World")
util.foo(util, "Hello World")

要使用点语法对此进行声明,请执行以下操作:

To declare this the same with the dot syntax you would do this:

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

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

这篇关于即使我已经用一个参数声明了函数,Lua函数也需要两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆