I am new to Lua, but not to programming. I have extensively used Java in the past. I decided the best way to learn Lua would be to do some reading around. I decided to implement a very basic version of object orientation and did the following:
Object = {
class = "object";
}
function Object:getClass()
return self.class;
end
function Object:printClass()
print(self:getClass());
end
print(Object:getClass()); --Returns "object"
print(Object["getClass"); --Returns the memory address of the function getClass()
print(Object["getClass"]()); --Should print the results of the function. Instead throws error "input:6: attempt to index a nill value (local self)" which, if I am understanding correctly, is the equivalent of a NullPointerException in Java.
Why does Lua throw the error above? What am I doing wrong? Is it possible to access functions with their string "name"? The question is NOT about how to use Lua in an object-oriented way, which has been answered here.
I tested the code here.
Because in Lua, Object:getClass()
is syntactic sugar for Object.getClass(Object)
(if you want to get technical, it only evaluates the expression Object
once). So when you call Object["getClass"]()
, you are calling the function with no parameters. That will cause a problem when the function tries to access its first parameter: self
, which will be nil
.
Hence the error, "attempt to index a nil value (local self)".
That's also where the magic variable self
comes from. When you declare a function with :
, the syntactic sugar adds a parameter to the front of the parameter list that it calls self
.