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.
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:
To declare this the same with the dot syntax you would do this:
or