|
1 | 1 | --- I like context managers for Python |
2 | 2 | --- I want them in Lua. |
3 | 3 |
|
| 4 | +---@class PlenaryContextManager |
4 | 5 | local context_manager = {} |
5 | 6 |
|
| 7 | +---@class PlenaryContextManagerObject |
| 8 | +---@field enter fun(self: PlenaryContextManagerObject): any |
| 9 | +---@field exit fun(self: PlenaryContextManagerObject) |
| 10 | + |
| 11 | +---@generic T, U |
| 12 | +---@param obj function|PlenaryContextManagerObject|thread |
| 13 | +---@param callable fun(arg: T): U? |
| 14 | +---@return U? |
6 | 15 | function context_manager.with(obj, callable) |
7 | 16 | -- Wrap functions for people since we're nice |
8 | 17 | if type(obj) == "function" then |
@@ -36,15 +45,16 @@ function context_manager.with(obj, callable) |
36 | 45 | return result |
37 | 46 | end |
38 | 47 | end |
39 | | - |
40 | | ---- @param filename string|table -- If string, used as io.open(filename) |
41 | | ---- Else, should be a table with `filename` as an attribute |
| 48 | +---If string, used as io.open(filename). Else, should be a table with `filename` as an attribute |
| 49 | +---@param filename string|{ filename: string } |
| 50 | +---@param mode? openmode |
| 51 | +---@return thread |
42 | 52 | function context_manager.open(filename, mode) |
43 | 53 | if type(filename) == "table" and filename.filename then |
44 | 54 | filename = filename.filename |
45 | 55 | end |
46 | 56 |
|
47 | | - local file_io = assert(io.open(filename, mode)) |
| 57 | + local file_io = assert(io.open(filename --[[@as string]], mode)) |
48 | 58 |
|
49 | 59 | return coroutine.create(function() |
50 | 60 | coroutine.yield(file_io) |
|
0 commit comments