-
Notifications
You must be signed in to change notification settings - Fork 11
/
mvc.lua
100 lines (77 loc) · 2.34 KB
/
mvc.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require('_class')
local Model = class()
function Model:ctor()
self.products = {
milk = {price = 1.50, quantity = 10},
eggs = {price = 0.20, quantity = 100},
cheese = {price = 2.00, quantity = 10}
}
end
function Model:get_product_list()
if not self.product_list_ then
self.product_list_ = {}
for key, value in pairs(self.products) do
table.insert(self.product_list_, key)
end
end
return self.product_list_
end
function Model:get_product_info(product, default)
return self.products[product] or default
end
local View = class()
function View:product_list(product_list)
print('PRODUCT LIST:')
for _, product in ipairs(product_list) do
print(product)
end
print()
end
function View:product_information(product, product_info)
print('PRODUCT INFORMATION:')
print(string.format('Name: %s, Price: %.2f, Quantity: %d\n',
product,
product_info.price,
product_info.quantity)
)
end
function View:product_not_found(product)
print(string.format('That product "%s" does not exist in the records', product))
end
local Controller = class()
function Controller:ctor()
self.model = Model.new()
self.view = View.new()
end
function Controller:get_product_list()
local product_list = self.model:get_product_list()
self.view:product_list(product_list)
end
function Controller:get_product_information(product)
local product_info = self.model:get_product_info(product, nil)
if product_info then
self.view:product_information(product, product_info)
else
self.view:product_not_found(product)
end
end
local controller = Controller.new()
controller:get_product_list()
controller:get_product_information('cheese')
controller:get_product_information('eggs')
controller:get_product_information('milk')
controller:get_product_information('arepas')
---------------------------------------------------------------------------
-- OUTPUT
---------------------------------------------------------------------------
-- PRODUCT LIST:
-- eggs
-- cheese
-- milk
-- PRODUCT INFORMATION:
-- Name: cheese, Price: 2.00, Quantity: 10
-- PRODUCT INFORMATION:
-- Name: eggs, Price: 0.20, Quantity: 100
-- PRODUCT INFORMATION:
-- Name: milk, Price: 1.50, Quantity: 10
-- That product "arepas" does not exist in the records