2

如何判断 Lua 脚本中的行号 x 是否会响应 Lua line hook

例子:

 1 first = 1
 2 
 3 function test ( data )
 4  if first == 0 then
 5    print ("\r\n")
 6  end
 7  print(data)
 8  --[[
 9  first = 0
10  ]]
11 end
12
13 test()
14

第 2、6、8、9、10、12 和 14 行不调用线路挂钩。加载并执行脚本后,我可以从 C/C++ 获取可执行行号表吗?

4

2 回答 2

2

lua_getinfo如果包含L在 中,则可以返回有效行表what

于 2013-12-12T18:49:41.177 回答
1

一些代码示例:

local exec_lines = {}

local function exec_line_counter(event, line)
    table.insert(exec_lines, line)$
end

local function count_exec_lines(lua_file)
    local external_chunk = loadfile(lua_file)

    debug.sethook(exec_line_counter, "l")
    external_chunk()
    debug.sethook()

    -- Removing `debug.sethook()` lines:
    table.remove(exec_lines, 1)
    table.remove(exec_lines, #exec_lines)
end

count_exec_lines("test.lua")

输出:

table.sort(exec_lines)
for i, num in ipairs(exec_lines) do
    print(num)
end

1

3

4

7

11

11 <--- 不知道为什么会重复。缺乏return?还是因为跟随tailcall

13

注意:它只会记录被解析的行。在您的测试用例中,它不包括第 5 行和第 6 行,因为first不是 0。

另一种解决问题的方法 - 只需简单地解析 Lua 源代码:计算和跳过仅包含 Lua 注释的行:

  • --lines

  • --[[ blocks ]]

编辑:啊,拍摄,编辑您使用 C/C++ 执行此操作的问题。挂钩函数也可以使用纯 C API 完成。如果您没有从我的回答中得到基本想法,可能会举个例子:)

于 2013-12-12T18:26:52.573 回答