-
Notifications
You must be signed in to change notification settings - Fork 53
Creating classes
Let us create a Window
class.
local class = require "30log" -- adds 30log to your code
local Window = class("Window") -- creates a class
That's it. The string argument Window is the name of the class.
Later on, we can query that name calling class.name
.
print(Window.name) -- outputs "Window"
Giving a class a name is optional though.
local unnamedWindow = class()
print(unnamedWindow.name) -- outputs nil
We can define attributes for any class.
Let us define a width
and a height
attributes for our Window
class and assign them values.
Window.width = 150
Window.height = 100
30log provides a shortcut, for convenience : passing an optional params
table (with named keys) as a second argument to class()
.
local Window = class("Window", {width = 150, height = 100})
print(Window.width) -- outputs 150
print(Window.height) -- outputs 100
When a class has a name
attribute, it is considered to be a named class.
In that case, calling tostring or print on that class (or any other function which triggers __tostring
metamethod) returns a string. This string specifies the passed-in object is a class, gives its name and memory address.
print(Window) -- outputs "class 'Window' (table: 0x0002cdc0)"
In case the class has not any named defined, it is considered to be an unnamed class, and this will be reported by a question mark symbol.
local Window = class(nil, {width = 150, height = 100})
print(Window) -- outputs "class '?' (table: 0x0002cdb8)"
This feature is mostly meant for debugging purposes.
Yet, one can define a custom __tostring
implementation for any class metatable.
local Window = class('Window')
getmetatable(Window).__tostring = function(t)
return "I am class "..(t.name)
end
print(Window) -- outputs "I am class Window"