lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Dirk Laurie once stated:
> 2017-03-04 8:32 GMT+02:00 Petri Häkkinen <petrih3@gmail.com>:
> > Why all the trouble? I mean, you could just use free functions:
> > object_system_func(a, b, c)
> >
> > This is faster (no need for nested dynamic table look ups) and
> > there is no need for "self" parameter that is magically more
> > important than the others.
> 
> I and others replied to the above in the thread "Lua and composition",
> but maybe it deserves a thread of its own.
> 
> Let me take an example from the only userdata objects supplied with
> Lua, namely files.
> 
> One can write:
> 
> io.open("results.txt","w"):write(table.concat(results,"\n")):close()

  I tried that code and I got:

lua: /tmp/xx.lua:3: attempt to index a nil value
stack traceback:
        /tmp/xx.lua:3: in main chunk
        [C]: ?

It took me awhile [1] to figure out the problem, and I had to rewrite the
program:

file,err = io.open("results.txt","w")
if not file then
  print(err)
  os.exit(1)
end

-- because io.write() doesn't work as expected
_,err = file:write(table.comcat(results,"\n"))
if not _ then
  print(err)
  os.exit(1)
end

io.close(file)

And then when I ran the code:

	results.txt: Permission denied

Ah!  

Object chaining like that is fine when there are no errors.  When there are,
it can be difficult to isolate the problem.  This point is orthogonal to
your point though.

> Without colon notation, how far can we get?
> 
> local outfile = io.open("results.txt","w")
> 
> Now what next? Remember, outfile:write() is not available.
> And io.write does not allow you to specify a file.

  And *that* is the biggest surprise for me in all this.  That io.write()
isn't the same as file:write() (just shows you how often I use io.write()).

  -spc (Some people love OOP, some people don't)

[1]	Not really, because this is a contrived example