How can I list all the functions included in a Lua source file?
For example, I have fn.lua which contains
function test1()
print("Test 1")
end
function test2()
print("Test 2")
end
And I wish to be able to display those function names (test1, test2) from another Lua script.
The only way I can figure at the moment is to include the file using require, then list the functions in _G - but that will include all the standard Lua functions as well.
Of course I could just parse the file manually using the string search functions, but that doesn't seem very Lua to me!
This will eventually form part of a process that allows the developer to write functions in Lua, and the operator to select which of those functions are called from a list in Excel (yuk!).
If you put them all in a "module" (which you should probably do, anyway):
mymodule = { }
function mymodule.test1()
print("Test 1")
end
function module.test2()
print("Test 2")
end
return mymodule
It becomes trivial:
mymodule = require"mymodule"
for fname,obj in pairs(mymodule) do
if type(obj) == "function" then
print(fname)
end
end
If you absolutely have to keep them in raw form, you'd have to load them in a different way to separate your global environment, and then iterate over it in a similar way (over the inner env's cleaned _G
, perhaps).
I see three ways:
Save the names in _G
before loading your script and compare to the names left in _G
after loading it. I've seen some code for this, either in the Lua mailing list or in the wiki, but I can't find a link right now.
Report the globals used in a function by parsing luac
listings, as in http://lua-users.org/lists/lua-l/2012-12/msg00397.html .
Use my bytecode inspector lbci from within Lua, which contains an example that reports globals.
If you want to do this, it's better to define the function is a package, as described in Programming in Lua book :
functions = {}
function functions.test1() print('foo') end
function functions.test2() print('bar') end
return functions
Then you can simply iterate your table functions
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.