Lua function expects two parameters even when I have declared the function with one parameter

為{幸葍}努か 提交于 2021-02-08 05:27:16

问题


Consider the Lua code below:

local util = {}

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

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

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")

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


回答1:


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

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")

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.

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

or

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


来源:https://stackoverflow.com/questions/4983263/lua-function-expects-two-parameters-even-when-i-have-declared-the-function-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!