Let's say I'm working with a lua library I installed using luarocks, and I want to see the definition of a function from that library. In ipython in could use
??function_name
to see the definition in the terminal, in matlab I could use
which function_name
then use my editor to look at the path returned by which. How could I do something similar to find the function definition for a lua library?
In 'plain' Lua/JIT, you can say
debug.getinfo
( func )
and will get a table containing (among others) the fieldsshort_src
,source
andlinedefined
.For Lua functions,
short_src
will be the filename orstdin
if it was defined in the REPL. (source
has a slightly different format, filenames are prefixed with an@
, a=
prefix is used for C functions or stuff defined interactively, and forload
ed functions, it will be the actual string that was loaded.)You can pack that up in a function like
or maybe even start an editor and point it there, e.g. (for vim)
And just for fun, here's yet another version that returns the code if it can find it somewhere. (This will also work for functions that have been generated at run time, e.g. by calling
load
, and where no source file exists. You could also work in the other direction by dumping theload
ed snippet into a temp file and opening that…)A closing remark: If you paste code into a Lua/JIT REPL,
local
s disappear between definitions, because every line (or minimal complete group of lines) is its own chunk. The common fix (that you probably know) is to wrap everything into a block asdo
*paste*end
, but an alternative is toload[[
*paste*]]()
(possibly with more=
s like[===[
and]===]
.) If you paste this way, the abovedumpsource
(or any other function usingdebug.getinfo
) will then be able to get the source of the function(s). This also means that if you defined a nice function but it's gone from the history and the scroll buffer, you can recover it in this way (if you defined it byload
ing and not directly feeding the interpreter). Saving the source in a file will then also be possible without copy-pasting and not require editing out the>>
prompts.