lua-users home
lua-l archive

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


I don't think I can entirely agree with this praise.

My problem is that globals make it too easy for a writer of a Lua script to pollute the Lua state by mistake, and I don't want to sandbox all my users scripts, because then some of the "good" mechanisms of globals wont work any more.

So one way would be the much discussed declaration of globals (which is the solution we use in our project, something similar to StrictLua).

And I think you can get rid of many problems with some syntactic sugar:
On 04/15/2013 08:38 AM, Dirk Laurie wrote:
You can tell the programs written by the supporters of this ideology.
They start out something like this:

    local pairs, ipairs, print, tostring, getmetatable, setmetatable
        = pairs, ipairs, print, tostring, getmetatable, setmetatable
One could add a new keyword: using, or import
     using pairs, ipairs, print, tostring, getmetatable, setmetatable
Would just do the same as you wrote, then

  using pairs, ipairs from table
would be the same as
  local pairs, ipairs = table.pairs, table.ipairs

actually it might even be possible to define a syntax without new keywords, maybe:
  local pairs, ipairs in _ENV
  local pairs, ipairs in require "table"
ect.

This is just an example. But in my view, something like that would be needed if we really want to use less globals, because I think the basic functions you need often should be easily available without writing a lot of - let's call it - unproductive code.

In Lua, it's a mistake, a Pythonic mistake, to think of local variables
as the usual thing. Local variables are special. You must declare them
explicitly. Their names don't survive compilation. You can have at
most 200 of them in one scope. They should be used with care, and only
for the purpose they were designed for, which is to be short-lived.
I don't think we would have upvalues in Lua if this was true. Actually I like upvalues the most as they live exactly as long as they need to. Local function and closures are my favorite "higher level" mechanisms in Lua :) I should write a "In praise of the closures" text :-)
Globals, on the other hand, don't have to be declared, have long-lived
names, and you can have as many as you like.

Well actually if you have a local table you can store as many off them as you want.

What would be great for me, is to ban globals as LHS values.
One would have to write _ENV.print = function donotprint() end instead of print = function donotprint()
but
  print "hello"
or
  local x = print
would still be allowed. I think that would be just fine because almost all mistakes with globals happen on the LHS. That means globals would be read only unless you access them via _ENV or _G.
-- 

Thomas