1

Moonscript 使用 \ 来调用方法,所以有人可以向我解释为什么下面的代码不起作用:

> file = io\open("mix.exs", "rb")
[string "tmp"]:1: calling 'open' on bad self (string expected, got table)

但是当你调用它来读取文件时呢?

> file\read!
"Code.ensure_loaded?(Hex) and Hex.start
4

2 回答 2

4

io.open函数期望获得一个字符串作为第一个参数,但io\open(就像io:open在 lua 本身中一样)实际上是将io表作为第一个参数传递。那就是方法调用。

io\open("file", "mode")/io:open("file", "mode")是 . 的语法糖io.open(io, "file", "mode")

这就是为什么file\read!没有显式参数的情况下工作的原因,因为file它作为第一个参数传递给read("file", "format")函数。

于 2015-02-12T14:23:39.863 回答
0

Moonscript uses \ to call methods

to call member methods. as in a\b c, ... translates to a.b(a,c,...).

this doesn't work here because io.open is a static function (io.open(what,how)), not a member (io.open(self,what,how)).

you couldn't call io:open in Lua either. the only place where io functions allow for being called as members is when you want to read/write stdio.

but when you call it to read the file it does ?

because now it's a member method of the file. you're actually still using io.read there, but the file object has io as a metatable index, therefore allowing you to access the same function via file.read, and since file\read! translates to file.read(file) it's the same thing.


so essentially the answer boils down to "because io:open doesn't work in Lua".

于 2019-08-15T12:37:47.653 回答