I am seeking a way to acquire all the functions which have been defined in the current scope from lua. Is there a quick way to implement it directly from lua, not from C? The factory functions are preferred to be included.
Asked
Active
Viewed 296 times
0
-
2Functions are values and values don't have scope. You probably want _variables_ that are in scope whose values are functions. If a value is a table, do you also want to recurse through its keys and values to find functions, too? And, of course, global variables are not declared at all; Do you want to consider those, too? – Tom Blodget Jul 18 '15 at 22:35
-
related: http://stackoverflow.com/questions/2834579/print-all-local-variables-accessible-to-the-current-scope-in-lua – ryanpattison Jul 18 '15 at 23:08
-
Also, keep in mind that "current scope" can only mean in a particular execution state. Each pass through the statement(s) where you check could give different results. – Tom Blodget Jul 19 '15 at 01:24
1 Answers
1
You can use a hybrid approach:
(1) to get all local variables, you can use debug.getlocal
and get the names and values of the variables (see for example the logic in this answer). All function values will have type
of the value equal to function
(type(value) == 'function'
), so you can easily filter based on that condition. The name of the variable will give you the name you are looking for (keep in mind that several names may refer to the same function).
(2) to get all global variables you can iterate over fields in _ENV
or _G
tables and apply the same filtering logic as in 1.
Note that neither of these methods gives you access to functions stored in table fields or available indirectly through metamethods.

Community
- 1
- 1

Paul Kulchenko
- 25,884
- 3
- 38
- 56