在Lua脚本层,Lua将所有的全局变量保存在一个常规的table中,这个table被称为全局环境,并且将这个table保存在一个全局变量_G中,也就是说在脚本中可以用_G获取这个全局table,并且有_G._G == _G,在默认情况,Lua在全局环境_G中添加了标准库比如math、函数比如pairs等。可以通过下面代码,可以递归打印_G中的所有信息:
- function treaverse_global_env(curtable,level)
- for key,value in pairs(curtable or {}) do
- local prefix = string.rep(" ",level*5)
- print(string.format("%s%s(%s)",prefix,key,type(value)))
- --注意死循环
- if (type(value) == "table" ) and key ~= "_G" and (not value.package) then
- treaverse_global_env(value,level + 1)
- elseif (type(value) == "table" ) and (value.package) then
- print(string.format("%sSKIPTABLE:%s",key))
- end
- end
- end
- treaverse_global_env(_G,0)