-
Notifications
You must be signed in to change notification settings - Fork 2
Classes
class cat
name {get set}
age {get set}
type {get }
constructor(name)
self.name = name
end
function isCat()
return true
end
static function coolCat()
return "coolCat!"
end
end
local thomas = cat.new("Thomas")
thomas:setAge(50)
thomas:setName("Thomas v2")
print(thomas:isCat()) -- outputs -> true
print(thomas:getName()) -- outputs -> "Thomas v2"
print(thomas:getAge()) -- outputs -> 50
Alright, well that's a cool demo, what does it mean?
So let's start with line #1 class cat This creates a class called cat
this class is global so if you'd like to do this locally, prefix the class with local
. If you don't know what metatables in Lua are, this might be tricky to understand. The simplest way to explain it is to think of this as an object and you can create a new object with different variables but the same attributes/behaviors.
So we go down to line #2 name {get set} this line generates getter and/or setter functions to be used in the script later on, for the time being, this is written in camel case, so getName
in this instance. the name in the above statement shows the actual name of the variable we're changing
Now line #6 the constructor: The constructor is a crucial part of creating a class, although it's not required it's recommended for most use cases. It allows for you in L++ to use something like class-name.new("hello",1337)
a constructor gets given a set of parameters to be used within the function, much like any other function the new instance of the class is called self in the constructor or any function within the class a constructor will ALWAYS return the instance of the new class.
Now line #9 an example of a class function. A class function function isCat()
these are just regular Lua functions but we append class, making Lua pass an instance of the class with each function call.
Now line #12 an example of a static class function static function coolCat()
What this means is, class.coolCat()
will now work exactly like a static class in another language like Java or C#.