Numeric for and Limits
Lesson 12 of 48 in Coddy's Lua for C Developers course.
A C for statement has separate initialization, condition, and update expressions. A Lua numeric for takes a start value, a limit, and an optional step. The default step is one. Its limit is inclusive when reached, so translating a strict C upper bound requires care.
The C example visits one and two because its condition is strictly less than three. The Lua example visits one, two, and three because three is the inclusive limit. For a C loop using i <= n, the Lua limit can be n directly. Bounds and step are evaluated once when the Lua loop starts; the control variable is local to the loop.
C
#include <stdio.h>
int main(void)
{
int total = 0;
for (int i = 1; i < 3; ++i) {
total += i;
}
printf("%d\n", total);
return 0;
}Lua
local total = 0
for i = 1, 3 do
total = total + i
end
print(total)Porting trap
Do not carry a strict C bound directly into the Lua limit. Descending traversal also requires an explicit negative step, such as for i = 3, 1, -1 do.
Challenge
EasyInput n is an integer from 0 through 100. Return the sum of integers from 1 through n, using a numeric loop.
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 PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler