【问题标题】:Is there any way to get source code from imported Lua module?有没有办法从导入的 Lua 模块中获取源代码?
【发布时间】:2019-05-12 21:50:21
【问题描述】:

是否可以从导入的 LUA 模块中完全反转代码?

例如我们有

mymath.lua

作为一个模块

local mymath =  {}

local a = 1

function mymath.add(a,b)
   print(a+b)
end

function mymath.sub(a,b)
   print(a-b)
end

function mymath.mul(a,b)
   print(a*b)
end

function mymath.div(a,b)
   print(a/b)
end

return mymath   

我们有

testmodule.lua

导入 mymath 模块

mymathmodule = require("mymath")

for key,value in pairs(mymathmodule) do
    print(key, value)
end

我设法打印出函数声明,但我无法得到参数或这些函数内部的内容。在 Python 中,我们可以反向导入模块,在 LUA 中有没有办法做到这一点?

【问题讨论】:

  • 从表面上看,这个问题似乎可以通过确定“require”如何找到“mymath.lua”来回答,因为这样你就可以读取文件了。你的问题比这更复杂吗?请edit更好地识别问题。

标签: lua


【解决方案1】:

只要您的程序可以访问未编译的源代码,您就只能使用常规 Lua 执行此操作。 debug.getinfo(f) 检索包含源文件名和定义函数的行号的表。以下是受Python中inspect.getsource(object)的启发:

local function inspectSource(f)
  local info = debug.getinfo(f, "S")
  if info.source and string.sub(info.source, 1, 1) == "@" then 
    local source = string.sub(info.source, 2) 
    local i = 0
    for line in io.lines(source) do
      i = i + 1
      if i > info.lastlinedefined then
        break
      end
      if i >= info.linedefined then
        print(line)
      end
    end
  end
end

用法:

mymathmodule = require("mymath")
inspectSource(mymathmodule.mul)

-- Output:
--          function mymath.mul(a,b)
--             print(a*b)
--          end     

还有很多需要改进的地方,但这是一个开始!照原样,以上假设模块源位于工作目录中。

【讨论】:

【解决方案2】:

Lua 没有内置机制来获取已编译的 Lua 代码并从中重新生成原始 Lua 文本。在许多情况下,信息只是丢失了;编译后参数名称和其他局部变量不以文本形式存在。

有各种各样的 Lua 反编译器,但即使它们也不能保证能够取回字符串。

话虽如此,你总是可以用你自己的替换 Lua 脚本模块加载器。加载程序从文件中读取字符串并对其进行编译,因此您的加载程序所要做的就是将该字符串存储在某个地方,以便您以后可以访问它。即便如此,这也不是一个简单的过程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多