查看_G表中内容
for k, v in pairs(_G) do
print(k, v)
end
运行结果
string table: 0042DFA8
xpcall function: 0042E7C0
package table: 0042DC60
tostring function: 0042E720
print function: 00247660
os table: 0042DF30
unpack function: 0042E780
require function: 0042ECA0
getfenv function: 00247500
setmetatable function: 0042E6E0
next function: 002475E0
assert function: 002473E0
tonumber function: 0042E700
io table: 0042DDF0
rawequal function: 002476A0
collectgarbage function: 00247420
arg table: 0042E1B0
getmetatable function: 00247540
module function: 0042EC60
rawset function: 00247700
math table: 0042E020
debug table: 0042E070
pcall function: 00247620
table table: 0042DD00
newproxy function: 00247BF8
type function: 0042E740
coroutine table: 0042DBC0
_G table: 00241AD8
select function: 0042E660
gcinfo function: 002474C0
pairs function: 00247BC8
rawget function: 002476C0
loadstring function: 002475C0
ipairs function: 00247B98
_VERSION Lua 5.1
dofile function: 00247440
setfenv function: 0042E6A0
load function: 00247580
error function: 00247480
loadfile function: 00247560
全局变量会被添加到 _G表中
区分全局变量和局部变量
a = 500
print(a)
local a = 300
print(a)
print("-----------------------")
for k, v in pairs(_G) do
print(k, v)
end
运行结果
500
300
-----------------------
a 500
......
环境路径
for k, v in pairs(package.loaded) do
print(k, v)
end
print("-----------------------------")
for k, v in pairs(package.preload) do
print(k, v)
end
print("-----------------------------")
print(package.path)
print("-----------------------------")
print(package.cpath)
运行结果
require 加载模块后会存入 package.loaded 中
require查找模块是否存在的顺序 package.loaded package.preload package.path package.cpath , 如果不在 package.loaded 中,而在其他路径下,则require后会加入 package.loaded 中。环境变量在函数中设置,方式1
-- test_1.lua
local a = {}
b = a
setmetatable(a, {__index = _G})
setfenv(1, a) -- 设置当前环境为a
function add(x, y)
return x + y
end
return a
-- test_2.lua
c = require "test_1"
print(c.add(1,2))
print(b.add(1,2))
print(test_1.add(1,2))
运行结果
3
3
3
环境变量在函数中设置,方式2
-- test_1.lua
module(...)
function add(x, y)
return x + y
end
-- test_2.lua
c = require "test_1"
print(c.add(1,2))
print(test_1.add(1,2))
运行结果
3
3
环境变量 setfenv 的用法
function func()
setfenv(1, {}) -- 设置当前函数的环境变量为空
print("hello") -- print 报错,当前环境没有print
end
print("world")
func()
运行结果
world
lua: test.lua:3: attempt to call global 'print' (a nil value)
stack traceback:
test.lua:3: in function 'func'
test.lua:7: in main chunk
[C]: ?
function func()
local a = {}
setmetatable(a, {__index = _G}) -- 设置元表
setfenv(1, a)
print("hello") -- print 就可以访问了
end
print("world")
func()
运行结果
world
hello