2

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 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

How do I invoke the foo method directly?
Thanks, the link helped me understand the concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.