-
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 = new cat("Thomas")
thomas:set_age(50)
thomas:set_name("Thomas v2")
print(thomas:isCat()) - outputs -> true
print(thomas:get_name()) - outputs -> "Thomas v2"
print(thomas:get_age()) - outputs -> 50
Alright, well that's a cool demo, what does it mean?
"class"
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 meta tables in Lua are, this might be tricky to understand. The simplest way to explain it is think of this like an object and you can create a new object with different variables BUT the same attributes/behaviors.
"get or set"
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 snake case, so get_name in this instance. the name in the above statement shows the actual name of the variable we're changing
"constructor"
Now line #6 the constructor: The constructor is 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 new classname("hello",1337) A constructor get's 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 constructor or any function within the class A constructor will ALWAYS return the instance of the new class.
"class functions"
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.
[WIP] "static class functions"
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#.
Safe, what is safe in L++? Safe is a way to make sure you're calling/editing/reading a
variable that you're actually sure exists. How do we use "safe" in L++? Well, simply we can
use my&.cool&.variable = 40 What this is the equivalent of doing is: if my and my.cool then return end.