Last active
September 22, 2024 02:26
-
-
Save remram44/5833870 to your computer and use it in GitHub Desktop.
Python's versus Lua's closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <functional> | |
| #include <iostream> | |
| #include <vector> | |
| int main() | |
| { | |
| std::vector<std::function<int (int)>> l; | |
| for(int i = 0; i < 10; ++i) | |
| l.push_back([=](int x) { return i + x; }); | |
| std::cout << l[2](3) << std::endl; // 5 | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| l = {} | |
| for i = 0, 10 do | |
| l[i] = function(x) return x + i end | |
| end | |
| print(l[2](3)) | |
| -- 5 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| l = [] | |
| for i in range(10): | |
| l.append(lambda x: x + i) | |
| print(l[2](3)) | |
| # 12 |
Author
The Python documentation refers to them as "cells", see for example in data model and PyFunction.
Cool, thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anyway, I also found this while curious about whether Python uses the term upvalue :P