lua-users home
lua-l archive

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


Peter Loveday wrote:
So, how does one use the new 'local global table' stuff ?

Here is my stab at modules in 5.0 using the new globals control. The Lua team did a good job of reducing the complexity of the original globals plan, and yet the result is still very powerful. There is no longer a need to write out table dereferences everywhere just to encapsulate things. I suppose classes will benefit equally well.

By the way, I can imagine adding some syntatic sugar for a namespace support which handles the common case used below. Synopsis:

    mymod = namespace
      local val
      function foo() ... end
        .
        .
        .
    end


-John


--------------------
-- define a module

local mod_init = function()
  -- a private variable
  local val

  -- a public function
  function foo(x)
    val = x
  end

  function bar()
    print(val)
  end
end

local G = getglobals()
local mod_table = { }
setmetatable(mod_table,{ __index = G })
setglobals(mod_init, mod_table)
mod_init()
--return mod_table
--   or
--some_global = mod_table

--------------------
-- test

do
  mod_table.foo(10)
  mod_table.bar()
  print(val, mod_table.val)
end




--
http:// i      .   /