lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

spir wrote:
[...]
> x = 1
> function f()
>   n = 1
>   function g(a)
>     print (x + n + a) 
>   end
>   return g
> end
[...]
> About implementation, it seems to indicate Lua embebs symbolic references (*) to outer _variables_ in reachable scopes, when creating a closure for g0.

You're correct. That's what it's doing --- because all your variables
are global. Your code is equivalent to:

_G["x"] = 1
_G["f"] = function()
  _G["n"] = 1
  _G["g"] = function(a)
    print (_G["x"] + _G["n"] + a)
  end
  return _G["g"]
end

You can see from this that globals aren't scoped --- every time you
access a global variable you're looking it up *by name* in the _G table.

You can change a function's _G using the setfenv() function; there are
lots of really cool things you can do with it, such as:

function createtable()
  local t = []
  setfenv(t, 1) -- change createtable's _G to point to t
  x = 1         -- create x key in t
  y = x + 1     -- create y key in t
  return t
end

But it's vitally important to remember that global accesses are table
lookups, and therefore slow --- you don't want to use them in
benchmarks. And it's also possible to get yourself into a horrible,
horrible mess if you're not really careful!

- --
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ "Sufficiently advanced incompetence is indistinguishable from
│ malice." -- Vernon Schryver
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAksTrKkACgkQf9E0noFvlzjEeQCg4Ox8PU7dXTk7dOquUDotN+kx
3ZsAoJRHiZwfnnCGqcPjFdHrma97mZbw
=BHh1
-----END PGP SIGNATURE-----