5 ms·
> <close> is equivalent to golang's defer [...] except at the block level. Does that mean it’s the same as C#'s `using` and Python's `with`?
by pansa2 6y ago
> <close> is equivalent to golang's defer [...] except at the block level.
Does that mean it’s the same as C#'s `using` and Python's `with`?
- anonymoushn 6y agoI wasn't deeply familiar with python's `with`, so I looked it up[0] <close> differs from `with` in at least the sense that it doesn't have any equivalent to __enter__ and doesn't create its own block. It creates a local variable whose __close metamethod will be called when it goes out of scope. Since Lua has lexical scope at the block level rather than the function level, this works similarly to the way Python calls __exit__. These snippets of Python and Lua are roughly equivalent. They both open a file, read one line, and close it, or do nothing if there was some error opening the file. try: with open("foo.txt") as f: print(f.readline()) # f is now closed. except: pass local f,err = io.open("foo.txt") if not err then local f <close> = f print(f:read("*l")) end -- f is now closed. C#'s `using`[1] seems much closer, except that it handles nulls by not trying to close them and lua's <close> does not include any such handling. [0]: https://docs.python.org/3/reference/compound_stmts.html#the-with-statement https://docs.python.org/3/reference/compound_stmts.html#the-... [1]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#the-using-statement https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
- frabert 6y agoThe reference manual https://www.lua.org/manual/5.4/manual.html#3.3.8 https://www.lua.org/manual/5.4/manual.html#3.3.8 seems to specify that "nil" and "false" values are ignored, so it behaves similarly to C#'s using.
- anonymoushn 6y agoOh, that's great!
- pull_my_finger 6y agoDo file descriptors come with a default __close metamethod or do you have to create your own?
- anonymoushn 6y agoThey come with one.