Menu
CoddyTech

Lambdas and Captures

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

A Lua closure captures variables, not values: an inner function keeps a reference to the outer local (an upvalue), so a later assignment to that local is seen by every closure that captured it. To freeze a value you copy it into a new local first. A C++ lambda says how it captures. [n] copies the value when the lambda is created, so later changes to n are not seen; [&n] refers to the variable itself, which matches Lua's behavior. A reference capture must not outlive the variable it refers to, or calling the lambda is undefined behavior.

Lua

local factor = 2
local f = function(x) return x * factor end
local snap
do
  local fixed = factor
  snap = function(x) return x * fixed end
end
factor = 3
print(f(4) .. " " .. snap(4))

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
int factor=2;
auto by_value=[factor](int x){return x*factor;};
auto by_ref=[&factor](int x){return x*factor;};
factor=3;
std::cout<<by_value(4)<<" "<<by_ref(4)<<"\n";
}

When porting a Lua closure, ask whether it should see later changes. If it should, capture by reference and keep the variable alive; if not, capture by value.

challenge icon

Challenge

Easy

Input: threshold on line one; integers on line two. Return how many values are strictly greater than threshold.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
int t=std::stoi(rows[0]);std::istringstream in(rows.size()>1?rows[1]:"");std::vector<int>v;int n;while(in>>n)v.push_back(n);std::cout<<above(v,t)<<"\n";
}
quiz iconTest yourself

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

All lessons in C++ for Lua Developers

Practice on your own: Online C++ compiler