function - 获取Lua脚本中的所有函数

标签 function lua

我正在尝试找出一种方法来获取 Lua 脚本中的所有函数。该脚本已通过loadfile编译成函数。例如,我想要获取下面脚本中定义的每个函数。

function example1()

end

local function example2()

end

local library = {}

function library:example3()

end

(function()
    -- Functions like this too.
end)

名称并不重要,我只是在寻找一种获取实际函数的方法,这样我就可以在 debug.getinfo 中使用它们并获取它们定义的行之类的信息。我有 LuaJIT,如果这使得这样就容易多了。这样的事情有可能吗?提前致谢。

最佳答案

我猜该文件将其函数声明为全局函数,否则很容易跟踪返回的内容。

如果是这种情况,您可以使用通用 for 循环循环遍历所有全局项,并且仅从中获取函数:

allFuncs = {}

for key, item in pairs(_G) do
    if type(item) == "function" then
        allFuncs[#allFuncs + 1] = item
    end
end

(_G是保存所有全局变量的表)

然后您将拥有一个列表 (allFuncs),其中包含声明的所有函数,但请注意,它还将包含默认函数,例如 setmetatablexpcall.

很容易修改代码来避免这种情况发生,但仅将其用于测试/学习:

function allFuncs()
    local funcsTab = {}
    for key, item in pairs(_G) do
        if type(item) == "function" then
            funcsTab[#funcsTab + 1] = item
        end
    end
    return funcsTab
end

defaultFuncs = allFuncs()

--then you load your file: other functions get declared
--we create another table containg the default + the new functions

myFuncs = allFuncs()

--then you subtract the first table from the second

for i = 1, #myFuncs do
    for o = 1, #defaultFuncs do
        if myFuncs[i] == defaultFuncs[o] then
            table.remove(myFuncs, i)
        end
    end
end

这是如果您的文件不返回任何内容并将其函数声明为全局函数。

如果文件将它们声明为本地文件,然后返回包含它们的表,则只需使用第一段代码将 _G 替换为返回的表。

关于function - 获取Lua脚本中的所有函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309901/

相关文章:

javascript - 如何在将来创建的元素上传递jquery函数事件

jquery - 检查函数是否动态存在

javascript - 验证 JavaScript 函数名称

lua - 如何: Communicate with a subprocess

arrays - Lua的混合数组和哈希表;它存在于其他任何地方吗?

lua - 一个Lua "Class"的两个实例是相同的 "object"

php - fatal error : Uncaught Error: Call to undefined function - have to use $this

swift - 函数calcDecrement返回类型中的 "()"是什么意思?

algorithm - 我需要 NodeMCU 中的 Lua 数学库

lua - 通过 Lua 脚本重启系统