Question

How Can I tell if line number x in a Lua script will respond to the Lua line hook?

Example:

 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

Line 2,6,8,9,10,12 and 14 does not call a line hook. After I have loaded and executed the script, can I some how, from C/C++, get a table of the executable line numbers?

Was it helpful?

Solution

lua_getinfo can return a table of valid lines if you include L in what.

OTHER TIPS

Some code sample:

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")

Output of:

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

is

1

3

4

7

11

11 <--- not sure why this duplicates. Lack of return? Or because following tailcall?

13

NOTE: it would log only lines being parsed. In Your test case, it does not cover 5th and 6th line, because first not being 0.

Another way of doing this and solving noted case - just simply parsing Lua source: counting and skipping lines which consists only of Lua comments:

  • --lines

  • --[[ blocks ]]

EDIT: ah, shoot, edited Your question of doing this with C/C++. Hooking functions can be done with plain C API too. Might make an example if You didn't get a basic idea from an my answer already made :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top