58 lines
1.0 KiB
Lua
58 lines
1.0 KiB
Lua
|
|
local function add(a, b)
|
||
|
|
return a + b
|
||
|
|
end
|
||
|
|
|
||
|
|
local function greet(name)
|
||
|
|
print("Hello, " .. name .. "!")
|
||
|
|
end
|
||
|
|
|
||
|
|
local Person = {}
|
||
|
|
Person.__index = Person
|
||
|
|
|
||
|
|
function Person:new(id, name, email)
|
||
|
|
local obj = {
|
||
|
|
id = id,
|
||
|
|
name = name,
|
||
|
|
email = email
|
||
|
|
}
|
||
|
|
setmetatable(obj, self)
|
||
|
|
return obj
|
||
|
|
end
|
||
|
|
|
||
|
|
function Person:__tostring()
|
||
|
|
return self.name .. " <" .. self.email .. ">"
|
||
|
|
end
|
||
|
|
|
||
|
|
local Repository = {}
|
||
|
|
Repository.__index = Repository
|
||
|
|
|
||
|
|
function Repository:new()
|
||
|
|
return setmetatable({items = {}}, self)
|
||
|
|
end
|
||
|
|
|
||
|
|
function Repository:add(key, item)
|
||
|
|
self.items[key] = item
|
||
|
|
end
|
||
|
|
|
||
|
|
function Repository:find(key)
|
||
|
|
return self.items[key]
|
||
|
|
end
|
||
|
|
|
||
|
|
function Repository:getAll()
|
||
|
|
local result = {}
|
||
|
|
for _, v in pairs(self.items) do
|
||
|
|
table.insert(result, v)
|
||
|
|
end
|
||
|
|
return result
|
||
|
|
end
|
||
|
|
|
||
|
|
local repo = Repository:new()
|
||
|
|
repo:add(1, Person:new(1, "Alice", "alice@example.com"))
|
||
|
|
repo:add(2, Person:new(2, "Bob", "bob@example.com"))
|
||
|
|
|
||
|
|
for _, p in ipairs(repo:getAll()) do
|
||
|
|
print(p)
|
||
|
|
end
|
||
|
|
|
||
|
|
print("3 + 4 = " .. add(3, 4))
|