Menu
CoddyTech

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 icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler