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!).
The Lua language provides numerous built-in methods that your program can call. For example, method print() to print the argument passed as input in console. A function is known with various names like a method or a sub-routine or a procedure etc.
This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table.
You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.
Functions are the main mechanism for abstraction of statements and expressions in Lua. Functions can both carry out a specific task (what is sometimes called procedure or subroutine in other languages) or compute and return values.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With