Numbers and Conversion
Lesson 4 of 48 in Coddy's Lua for C++ Developers course.
Lua 5.1 has one number type, normally double-precision floating point, rather than separate C++ integer and floating types. Integer precision is finite. C++ integer division truncates toward zero, and its remainder follows that quotient. Lua / performs floating division; math.floor(n / d) rounds the quotient downward. Lua % uses a floor quotient, so a positive divisor gives a nonnegative remainder. With negative inputs this differs from C++ even when both operands began as integers. Convert input text explicitly with tonumber; invalid numeric text produces nil. Check conversion when the input contract allows invalid text.
C++17
Inside main, with standard headers supplied:
std::cout << (-7 / 3) << ":" << (-7 % 3) << "\n";Lua 5.1
print(math.floor(-7 / 3) .. ":" .. (-7 % 3))Porting trap
Do not translate C++ integer division into plain Lua / and expect an integer result. For this exercise, the required operation is floor division, including negative dividends. Use the contract to choose the quotient, rather than copying C++ truncation behavior.
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 C++ 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 Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler