示例工程 17-oop-patterns

17-oop-patterns/02-class-table/main.lua

lua · 0.6 KB

-- @runtimes lua54 luajit
--- 演示:类表 + __index 共享方法。
local M = {}
 
local Account = {}
Account.__index = Account
function Account.new(balance)
	return setmetatable({ balance = balance }, Account)
end
function Account:deposit(amount)
	self.balance = self.balance + amount
	return self.balance
end
 
--- @return table { first = integer, second = integer }
function M.run(log)
	log = log or print
	local account = Account.new(10)
	local first = account:deposit(5)
	local second = account:deposit(2)
	log(("first=%d second=%d"):format(first, second))
	return { first = first, second = second }
end
 
if not ... then
	M.run()
end
return M