cheat-sheet-lua/support/class.lua

102 lines
2.2 KiB
Lua

-- ============================================================================
-- This is a simple Person class (Raw example without synthetic sugar).
-- ============================================================================
Person1 = {}
-- Constructor
function Person1.new(self, name, age)
local o = {}
self.__index = self
setmetatable(o, self)
o.name = name
o.age = age
return o
end
-- Methods
function Person1.getName(self)
return self.name
end
function Person1.getAge(self)
return self.age
end
-- Usage
local instance = Person1.new(Person1, "John", 30)
print('name: ' .. instance.getName(instance)) -- John
print('age: ' .. instance.getAge(instance)) -- 30
-- Garbage collection
Person1 = nil
instance = nil
-- ============================================================================
-- This is a simple Person class (Synthetic sugar example).
-- ============================================================================
Person2 = {}
-- Constructor
function Person2:new(name, age)
local o = {}
self.__index = self
setmetatable(o, self)
o.name = name
o.age = age
return o
end
-- Methods
function Person2:getName()
return self.name
end
function Person2:getAge()
return self.age
end
-- Usage
local instance = Person2:new("John Doe", 50)
print('name: ' .. instance:getName()) -- John Doe
print('age: ' .. instance:getAge()) -- 50
-- Garbage collection
Person2 = nil
instance = nil
-- ============================================================================
-- This is my class definition method (with Synthetic sugar example).
-- ============================================================================
Person = {}
-- Constructor
function Person:new(name, age)
local this = setmetatable({}, {__index = self})
this.name = name or 'EndMove'
this.age = age or 20
return this
end
-- Methods
function Person:getFName()
return 'name: ' .. self.name
end
function Person:getFAge()
return 'age: ' .. self.age
end
-- Usage
local instance = Person:new("Gashy", 21)
print(instance:getFName()) -- name: Gashy
print(instance:getFAge()) -- age: 21
-- Garbage collection
Person = nil
instance = nil
-- ============================================================================
-- Thanks for reading!