Lua基础:环境

Lua 用一个名为 environment 普通的表来保存所有的全局变量。

  1. for n in pairs(_G) do     --打印所有全局变量的名字
  2.      print(n)
  3. end

动态名字访问全局变量:

  1. function getfield(f)
  2.     local v=_G                      --全局变量表
  3.     for w in string.gfind(f,"[%w_]+") do
  4.         v=v[w]
  5.     end
  6.     return v
  7. end
  8.  
  9. function setfield(f,v)
  10.     local t=_G             --全局变量表
  11.     for    w,d in string.gfind(f,"([%w_]+)(.?)") do
  12.         if d=="." then
  13.             t[w]=t[w] or {}     --创建一个表
  14.             t=t[w]         --获取表
  15.         else
  16.             t[w]=v
  17.         end
  18.     end
  19. end
  20.  
  21. setfield("t.x.y",10)
  22. print(t.x.y)
  23. print(getfield("t.x.y"))

声明全局变量:

  1. setmetatable(
  2.     _G,{
  3.         _newindex=function(_,n)
  4.             error("attempt to write to undeclared variable" .. n,2)
  5.         end,
  6.         _index=function(_,n)
  7.             error("attempt to read undeclared variable " .. n,2)
  8.         end
  9.     }
  10. )
  11.  
  12. function declare(name,initval)
  13.     rawset(_G,name,initval or false)
  14. end
  15. if rawget(_G, var) == nil then
  16.     print("Hello")
  17. end
  18. ------------------------------------------------------------------
  19. local declaredNames = {}
  20.  
  21. function declare (name, initval)
  22.      rawset(_G, name, initval)
  23.      declaredNames[name] = true
  24. end
  25.  
  26. setmetatable(_G, {
  27.      __newindex = function (t, n, v)
  28.     if not declaredNames[n] then
  29.          error("attempt to write to undeclared var. "..n, 2)
  30.     else
  31.          rawset(t, n, v) -- do the actual set
  32.     end
  33. end,
  34.      __index = function (_, n)
  35.     if not declaredNames[n] then
  36.          error("attempt to read undeclared var. "..n, 2)
  37.     else
  38.          return nil
  39.     end
  40. end,
  41. })
     

非全局的环境:

  1. a=1
  2. setfenv(1,{_G=_G})
  3. _G.print(a)       --nil
  4. _G.print(_G.a)  --1
  5. ------------------------------------------------------
  6. a = 1
  7. local newgt = {}       -- create new environment
  8. setmetatable(newgt, {__index = _G})
  9. setfenv(1, newgt)   -- set it
  10. print(a)                   --> 1
  11. ------------------------------------------------------
  12. a=10
  13. print(a)            --10
  14. print(_G.a)         --10
  15. _G.a=20
  16. print(_G.a)         --20
     

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/88078385