Menu
CoddyTech

Receiver Arguments and Colon

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

In C, a function that changes a record normally receives a pointer to that record. The caller explicitly passes its address, and the callee uses the pointer to reach the fields. Lua methods follow a similar receiver convention, but a table reference already identifies the object. Defining a function with a colon supplies a first parameter named self. Calling with a colon supplies the receiver argument. A dot call is also valid when you pass that receiver yourself, as the second call demonstrates.

C

#include <stdio.h>
struct Counter { int n; };
static void counter_add(struct Counter *self, int amount)
{
    self->n += amount;
}
int main(void)
{
    struct Counter counter = {2};
    counter_add(&counter, 3);
    counter_add(&counter, 4);
    printf("%d\n", counter.n);
    return 0;
}

Lua

local counter = {n = 2}
function counter:add(amount)
  self.n = self.n + amount
end
counter:add(3)
counter.add(counter, 4)
print(counter.n)

Porting trap

Lua does not bind a receiver merely because a function was retrieved from a table. Calling counter.add(3) would pass the number as self. Use counter:add(3) or counter.add(counter, 3).

challenge icon

Challenge

Easy

Model.new(n) stores n. Implement Model:add(delta), updating n and returning it. Input has initial n followed by one delta. The app invokes the colon method and returns its result.

Edit app.lua, model.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.

Public API checks: Model.new(n) stores independent n state. add(delta) returns and stores the updated n, including negative and zero deltas. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local Model=require("model")
local a,b=Model.new(2),Model.new(10)
assert(a:add(3)==5 and a.n==5,"add must return and store the updated n")
assert(a:add(-7)==-2 and a:add(0)==-2,"add must support negative and zero deltas")
assert(b.n==10,"add must not mutate another instance")
end
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