lua-users home
lua-l archive

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


On 14/07/2011 9.06, Peter Odding wrote:
Patrick Donnelly wrote:
Use debug.getinfo to see if your replacement print function is being
called from the first function on the call stack (the interpreter).

Luiz Henrique de Figueiredo wrote:
lua.c runs lines entered interactively using this:
	status = luaL_loadbuffer(L, line, l, "=stdin");

So you can check whether the source is "=stdin":
	print(debug.getinfo(1).source)

Thanks for these suggestions Patrick and Luiz! I'm thinking it may not
be optimal to call debug.getinfo() every time my redefined print()
function is called (because it may be called thousands of times even for
trivial scripts that call print() in a loop) but of course I can just
not redefine print() when debug.getinfo(1).source ~= '=stdin'.

You could conditionally redefine print, instead of redefining print unconditionally and checking every time if source is stdin (untested code):

-- wherever you redefine print write:
print = (function()
  if debug.getinfo(2).source == '=stdin' then
    return prettyprint -- this is your function
  else
    return print -- default print
  end
end)()

alternatively you can define your prettyprint inline

print = (function()
  if debug.getinfo(2).source == '=stdin' then
    return function(...)
     -- prettyprint body
    end
  else
    return print -- default print
  end
end)()





  - Peter