回顾:账户对象
Coddy 面向 GDScript 开发者的 Lua 课程的第 36 课,共 48 课。
挑战
中等在 model.lua 中实现 Model.new(balance) 和 Model:withdraw(amount)。只有当 amount 非负且余额足够时,withdraw 才返回 true 并扣除金额。输入内容是初始余额,后面依次是取款金额。返回 finalBalance:acceptedCount。操作失败时,余额保持不变。
编辑 app.lua、model.lua。可见但已锁定的 main.lua 会将 stdin 读入一个行序列,调用 app.run(lines),并输出其返回值,末尾带一个换行符。不要输出诊断信息,也不要更改模块名称。输入为空时,会得到一个空序列。所有数值输入都足够小,不会导致溢出。
公共 API 检查:withdraw 返回布尔值;金额为负数或余额不足时,余额保持不变;取款金额为零或恰好等于余额时,操作成功;不同账户彼此独立。已锁定的驱动程序会在调用 app.run 之前检查这些行为。检查成功时不会输出任何内容。
亲手试试
-- 公共 API 检查
do
local Model=require("model")
local a,b=Model.new(5),Model.new(8)
assert(a:withdraw(6)==false and a.balance==5,"overdraft must leave balance unchanged")
assert(a:withdraw(-1)==false and a.balance==5,"negative withdrawal must not mutate")
assert(a:withdraw(0)==true and a.balance==5,"zero withdrawal is valid")
assert(a:withdraw(5)==true and a.balance==0,"exact withdrawal succeeds")
assert(b.balance==8,"accounts must be independent")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
面向 GDScript 开发者的 Lua中的所有课
自己练习: Lua 在线编译器