Print in recent versions should just put a space between each item (it used to use tabs, and if you are running lua on your PC, it will obviously still use them) I changed this because the CHDK console doesn't actually understand tabs, and with the limited space, it wouldn't be useful to implement them. This is still annoyingly different from write, which doesn't do any formatting.
For consistency, it may be worth writing a wrapper for write that behaves like print (add spaces and tostring anything that needs it.) Actually, in the long run stdout:write() should just go to the console
Your recent version is was pretty much what I had in mind. I agree that mylog=require("log").open("mylog.log") is probably too scary for the general scripter.
What follows is purely for educational purposes on a fairly advanced lua concept. If it doesn't make sense, don't worry too much.
There is an important difference between:
function foo()
local t={}
function t.bar()
-- stuff
end
return t
end
and
local function bar()
-- stuff
end
function foo()
local t={}
t.bar = bar
return t
end
The first version creates a new function (actually, a
closure, see also
lua specific description) for each call to foo, so bar in each returned t refers to a different function, and that function gets it's own copy of any local variables it uses from the enclosing foo. The second assigns the same function to the bar member of every t, and that function has no access to the local variables of foo.
Note above that I've made bar local, which makes it private to the enclosing block (modules loaded by require are implicitly blocks). This does not affect the lifetime of the function: It will exist for as long as something has a reference to it, but nothing outside the module will be able to use it. For functions internal to a module, this is preferable to using a global, or putting it in the table that forms the interface of the module.
If you plan to use object syntax (t:bar()) you'd have to explicitly include the self parameter in the declaration, e.g.
local function bar(self,...)
end
Finally, note that because you've used closures, you don't actually need the self parameter, and so using object syntax is just extra baggage. This is demonstrated by the fact you used newlog.handle:write() instead of self.handle:write(). If you use closures, you may as well just have your users use log.print() because each copy of the print function knows who it belongs to.
If you don't need the special characteristics of closures, the second method is more efficient. OTOH, closures are an incredibly powerful concept, and arguably more elegant the lua "syntactic sugar" object system.
In your case, this doesn't matter which method you use, because the functions are trivial, and people are at most going to open a handful of logs.