Menu
CoddyTech

Functions and Arguments

Lesson 17 of 48 in Coddy's Lua for C Developers course.

C function declarations specify parameter and return types. Lua uses function ... end without type declarations, and local function keeps the function name local. A function is a value that can be assigned or passed to another function, much as a C function pointer selects behavior. Numeric parameters receive values, so rebinding a parameter does not update the caller. A table parameter still refers to the caller's table, allowing field mutations through that shared reference. The examples compute a result and return it to the caller before printing.

C

#include <stdio.h>
static int twice(int x) {
    return x * 2;
}
int main(void) {
    printf("%d\n", twice(4));
    return 0;
}

Lua

local function twice(x)
  return x * 2
end
print(twice(4))

Porting trap

A declared C prototype constrains argument count. Lua fills omitted parameters with nil and discards extra arguments unless the function accepts varargs. Validate required values before doing arithmetic.

challenge icon

Challenge

Easy

Input is integer unit price and nonnegative integer quantity on two lines. Define a local function subtotal(price, quantity) and return its result.

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