To add a little (I hope) more to the explanations...
The behavior of "self" in Lua is not quite the same the behavior of self/this in say C++, Java, PHP etc. In those languages, the self/this is inherently available on any methods that are defined within the classes. It is essentially invalid to invoke the methods in a way in which self/this is not available. Unless you explicitly define a method as static, you can be assured that self/this is available.
In Lua, the situation is much murkier. "self" really only exists by convention. The ":" method invocation syntax is actually kind of a "trick," (something people like to call syntactic sugar). Honestly, I am not a big fan of this aspect of the language.
Here is a code snippet that demonstrates this point:
Code: Select all
local foo = {
x = 5,
}
function foo.bar( self )
if self then
print("In bar, self exists and self.x is " .. tostring(self.x))
else
print("In bar, self is nil")
end
end
function foo:czar()
if self then
print("In czar, self exists and self.x is " .. tostring(self.x))
else
print("In czar, self is nil")
end
end
foo.bar()
foo:bar()
foo.bar(foo)
foo.czar()
foo:czar()
foo.czar(foo)
Note that the function "bar" is defined somewhat oddly. The reality is that when you define a function in Lua using the ":" operator, it's really being defined as you see "bar" defined. Thus, the definition of "czar" is equivalent to the definition of "bar." The funky thing, though, is that it's actually the invocation of the function that is key. If you don't invoke the function with the ":" operator (or explicitly pass the table you're using), then the method does not have access to "self"
This may be somewhat confusing, but if you pay close attention to this code example, it should be clear why your code is not doing what you want it to.