开发者

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

Consider the Lua code below:

local util = {}

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

util.foo("Hello World")
util.foo(n开发者_如何学Pythonil, "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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜