Validation Before Mutation
Lesson 32 of 48 in Coddy's Lua for GDScript Developers course.
Porting a stateful GDScript method requires preserving when mutation occurs, not only its arithmetic. Check the withdrawal amount before subtracting it from the account. An invalid amount must leave the original balance intact. In Lua, the same rule applies whether the function reports a boolean status, returns a message, or raises an error. A protected call does not roll back mutations made before failure. The examples use an ordinary dictionary or table and return a boolean so the caller can format a result. Zero is a valid withdrawal; negative amounts and amounts above the balance are rejected.
GDScript 4
extends SceneTree
func withdraw(account, amount):
if amount < 0 or amount > account["balance"]:
return false
account["balance"] -= amount
return true
func _init():
var account = {"balance": 10}
var ok = withdraw(account, 12)
print(("ok:" if ok else "invalid:") + str(account["balance"]))
quit()Lua 5.1
local function withdraw(account, amount)
if amount < 0 or amount > account.balance then return false end
account.balance = account.balance - amount
return true
end
local account = {balance = 10}
local ok = withdraw(account, 12)
print((ok and "ok:" or "invalid:") .. account.balance)Porting trap
Do not subtract first and then rely on pcall to undo a rejected withdrawal. Lua error handling provides no automatic state rollback.
Challenge
EasyInput is nonnegative balance and an integer withdrawal amount. Reject negative amounts or amounts exceeding the balance. Return ok:newBalance or invalid:originalBalance. Zero is valid.
Edit app.lua. The visible locked main.lua 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.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Validation Before MutationTables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account Objects2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler