Reputation: 8533
Moonscript uses \ to call methods so can someone explain to me why the code below does not work:
> file = io\open("mix.exs", "rb")
[string "tmp"]:1: calling 'open' on bad self (string expected, got table)
but when you call it to read the file it does ?
> file\read!
"Code.ensure_loaded?(Hex) and Hex.start
Upvotes: 1
Views: 296
Reputation: 1142
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".
Upvotes: 0
Reputation: 80961
The io.open
function expects to get a string as the first argument but io\open
(like io:open
in lua itself) is actually passing the io
table as the first argument. That is it is a method call.
io\open("file", "mode")
/io:open("file", "mode")
are syntactic sugar for io.open(io, "file", "mode")
.
This is why file\read!
works without an explicit argument because file
gets passed as the first argument to the read("file", "format")
function.
Upvotes: 4