5

how can one get the caller of function within a function in lua?

Specifically I'm looking (for debug purposes in the command output, e.g. print) the ability to log when a common function is called, with an indication of where it was called from.

This could be just the filename of where it was called from for example

i.e.

File 1 - Has commonly used function 

File 2 - Calls of the the file one functions

PS Mud - I actually get a nil when doing this - is this normal then? No way to get more info in this case:

Called file;

SceneBase = {}
  function SceneBase:new(options)
  end
return SceneBase

Calling file:

require("views.scenes.scene_base")
local scene = SceneBase.new()

2 Answers 2

10

debug.getinfo(2).name will give you the name of the calling function if it has one and it is a string. If it's an anonymous function, you'll get nil, if it's stored in a table using something other than a string key, you'll get ?.

function foo() print(debug.getinfo(2).name) end

-- _G["foo"] => function name is a string
function bar() foo() end
bar() --> 'bar'

-- _G[123] => function name is a number
_G[123] = function() foo() end
_G[123]() --> '?'

-- function has no name
(function() foo() end)()  --> 'nil'
2
  • thanks - I'm getting a "nil" in the case I have - I put as a PS in my original post - no way to get more info here?
    – Greg
    May 14, 2012 at 21:02
  • name gives you the calling function name. In your example, there is no name (the calling function is a compiled Lua file, and the chunk isn't assigned to anything with a name). If you want to the name of the calling file, then you can use source or short_src instead of name.
    – Mud
    May 14, 2012 at 22:09
0

The Lua debug library lets you get the stack trace.

1
  • I see that with "print ("Info: ", debug.getinfo(1).short_src)" I can get info on the current function. But replacing the getinfo parameter with a 2 to get details of the function that called it didn't seem to work. Am I on the right track here?
    – Greg
    May 14, 2012 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.