您的位置:首页 > 编程语言 > Lua

Lua之sethook学习

2015-06-17 00:27 302 查看

debug.sethook ([thread,] hook, mask [, count])

Sets the given function as a hook.The string
mask
and the number
count
describewhen the hook will be called.The string mask may have the following characters,with the given meaning:

"c"
:
The hook is called every time Lua calls a function; 当函数被调用的时候触发,且在函数获得参数之前调用;

"r"
:
The hook is called every time Lua returns from a function; 当函数返回之前触发hook,且不能在此时获得函数的返回值;

"l"
:
The hook is called every time Lua enters a new line of code. 当执行到某一行代码之前触发hook

With a
count
different from zero,the hook is called after every
count
instructions.

When called without arguments,debug.sethook turns off the hook.

When the hook is called, its first parameter is a stringdescribing the event that has triggered its call:
"call"
,
"return"
(or
"tail return"
),
"line"
, and
"count"
.For line events,the hook also gets the new line number as its second parameter.Inside a hook,you can call
getinfo
with level 2 to get more information aboutthe running function(level 0 is the
getinfo
function,and
level 1 is the hook function),unless the event is
"tail return"
.In this case, Lua is only simulating the return,and a call to
getinfo
will return invalid data.

debug.getinfo(n)

n = 0 : 表示getinfo本身;

n = 1: 表示hook函数;

n = 2: 表示当前正在运行的函数;

debug.sethook(

optional thread,



hook function,



hook mask , -- string with "c" and/or "r" and/or "l"

optional instruction count) --[b]instruction指令行统计[/b]

下面举个例子,如何使用sethook来定位出错的代码在哪一行:

function test1()
c = nil
a = 1
b = a + 3
print(b)
print(c.x)
end

function test2()
c = {}
table.insert(c,1)
print("table size is : ".. #c)
end

function hook()
print(debug.traceback())
end
debug.sethook(hook,"l")

test1()


输出堆信息如下:

>lua -e "io.stdout:setvbuf 'no'" "test.lua"
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:21: in main chunk
[C]: ?
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:3: in function 'test1'
test.lua:21: in main chunk
[C]: ?
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:4: in function 'test1'
test.lua:21: in main chunk
[C]: ?
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:5: in function 'test1'
test.lua:21: in main chunk
[C]: ?
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:6: in function 'test1'
test.lua:21: in main chunk
[C]: ?
4
stack traceback:
test.lua:17: in function <test.lua:16>
test.lua:7: in function 'test1'
test.lua:21: in main chunk
[C]: ?
lua: test.lua:7: attempt to index global 'c' (a nil value)
stack traceback:
test.lua:7: in function 'test1'
test.lua:21: in main chunk
[C]: ?
>Exit code: 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: