Floor Division and Numbers
Lesson 3 of 29 in Coddy's Lua for Luau Developers course.
Luau and the usual Lua 5.1 build both use double-precision numbers. Removing annotations does not add arbitrary precision or an integer subtype. Luau provides // for floor division; Lua 5.1 needs math.floor(a / b). Negative inputs expose the difference between flooring and truncating toward zero. The remainder operator % pairs with floor division here. Numeric conversion remains explicit at input boundaries: tonumber returns nil for invalid decimal text. Test that result before arithmetic when your contract allows malformed input. This task supplies valid bounded integers and a positive divisor.
Luau
local q: number = -7 // 3
print(`{q}:{-7 % 3}`)Lua 5.1
print(math.floor(-7 / 3) .. ":" .. (-7 % 3))Porting trap
Do not replace floor division with math.modf. For a negative nonintegral quotient, truncation produces the wrong integer.
Challenge
EasyInput has integer n on line one and positive integer d on line two. Return floor quotient and remainder separated by a colon.
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 Luau Developers
1Syntax and Runtime
Run Lua ModulesInterpolation to TextFloor Division and NumbersBytes and UTF-8 LibrariesFalse Values and DefaultsConditional ExpressionsPractice on your own: Online Lua compiler