lua-users home
lua-l archive

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


I have overloaded the standard `print` function every time I have introduced Lua in a project.
This was especially useful given the fact that for example LuaDura defines a handy and often used `function printf (format, ...) print(format:format(...)) end` and a `dura.dump` for deep display of tables.

Examples of overloads: calling `OutputDebugString` on Windows driver, filling the log buffer in the printer firmware, displaying in a `MessageBoxA` when run through `rundll32`...

There is nothing magical about `print`, but the fact that it calls `tostring` on all arguments, concatenates them with a tabulation and adds a newline complicates the overload.
It would have been simpler if there were a hidden function like `_print` that just outputs a _single_ line of text.
In LuaDura, here is how I redefined `print` :

    if not _print then _print = print end
    function print(...)
        local t = {}
        for i=1,select('#',...) do
            t[i] = tostring(select(i, ...))
        end
        t = table.concat(t, "\t").."\n"
        for s in t:gmatch("([^\n]*)\n") do
            _print(s)
        end
    end

The split in lines at the end of the function is often useful, notably for good formatting with `OutputDebugString`.