Recap: Account Objects
Lesson 24 of 35 in Coddy's Luau for Lua Developers course.
Challenge
MediumImplement Model.new(balance) and Model:withdraw(amount) in model.luau. Withdraw returns true and subtracts only when amount is nonnegative and affordable. Input is initial balance followed by withdrawal amounts. Return finalBalance:acceptedCount. Failed operations leave balance unchanged.
Edit app.luau, model.luau. The visible locked main.luau reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Public API checks: withdraw returns a boolean; negative or unaffordable amounts leave balance unchanged, zero and exact-balance withdrawals succeed, and accounts are independent. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
Try it yourself
-- Public API checks
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))
All lessons in Luau for Lua Developers
4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Tables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account ObjectsPractice on your own: Online Luau compiler