lua 反射


lua 反射

      

debug实现反射功能:获取函数信息、函数局部变量、函数使用的外部局部变量等

      

             

                                

函数信息

         

getinfo(thread, f, what):获取函数的表信息

Returns a table with information about a function. You can give the 
function directly or you can give a number as the value of f, which 
means the function running at level f of the call stack of the given 
thread: level 0 is the current function (getinfo itself); level 1 is 
the function that called getinfo (except for tail calls, which do not 
count in the stack); and so on. If f is a number greater than the 
number of active functions, then getinfo returns fail.
* 以表的形式返回函数的信息
* f可以直接指定为函数、函数的栈
* f=0:getinfo函数
* f=1:调用getinfo的函数fun
* f=2:调用fun的函数
* 如果没有函数信息,返回nil
* 说明:f从0往上表示调用该函数的函数,不能向下(该函数调用的函数)

The returned table can contain all the fields returned by lua_getinfo, 
with the string what describing which fields to fill in. The default 
for what is to get all information available, except the table of 
valid lines. If present, the option 'f' adds a field named func with 
the function itself. If present, the option 'L' adds a field named 
activelines with the table of valid lines.
* 默认会返回所有函数的信息
* what=f:表中添加字段func,value为函数自己
* what=L:表中添加字段activelines,表示函数的有效行(排除空行、只包含注释的行)

For instance, the expression debug.getinfo(1,"n").name returns a name 
for the current function, if a reasonable name can be found, and the 
expression debug.getinfo(print) returns a table with all available 
information about the print function
* debug.getinfo(1,"n").name:返回表中name对应的值(函数的名字)
* debug.getinfo(print):返回print函数的表信息

        

示例

huli@hudeMacBook-Pro lua % cat f.lua
function fun()
  for key,value in pairs(debug.getinfo(0)) do print(key,value) end
  print()

  for key,value in pairs(debug.getinfo(1)) do print(key,value) end
  print()

  for key,value in pairs(debug.getinfo(2)) do print(key,value) end
end

fun()


-- 运行脚本
huli@hudeMacBook-Pro lua % lua f.lua
name	getinfo  --函数的名称
ntransfer	0
source	=[C]     --函数定义的位置:定义在字符串中(如c函数)、文件中(以@开头的文件)
namewhat	field
currentline	-1
func	function: 0x10ebb9d20
istailcall	false
ftransfer	0
short_src	[C]
lastlinedefined	-1
linedefined	-1
nparams	0         --函数参数的个数
isvararg	true  --函数参数是否可变
what	C         --函数的类型:可为C、lua、main
nups	0         --函数使用的外部局部变量(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值