Stricter Modules - noooway/love2d_arkanoid_tutorial GitHub Wiki

In part 2-01 I've been talking about splitting the code into several files.

I've adopted a convention that each variable or function declaration should be either local or go into module table. The problem of such approach is that it is easy to forget declare a variable local. In that case, the variable is defined in the global environment.

There are several approaches to avoid this. Some of them can be found here: http://lua-users.org/wiki/ModulesTutorial

Let's again take a look at greetings.lua module from 2-01.

local greetings = {}  --(*1)

greetings.hello_message = "Hello from Greetings module."

function greetings.say_hello()
  print( greetings.hello_message )
end

local secret = "IDDQD"

function greetings.reveal_secret() 
  print( secret )
end

function make_mess()
   mess = "terrible"
end

return greetings --(*2)
local print = print              --(*1)

local stricter_greetings = {}
if setfenv then
  setfenv( 1, {} )  -- for Lua 5.1                   --(*2)
else
  _ENV = nil        -- for Lua 5.2 and newer         --(*2)
end

local hello_message = "Hello from Stricter Greetings module."

function stricter_greetings.say_hello()
  print( hello_message )
end

local secret = "IDDQD"

function stricter_greetings.reveal_secret() 
  print( secret )
end

function stricter_greetings.make_mess()
   mess = "terrible"               --(*3)
   -- local mess = "terrible"      
end

return stricter_greetings

(*1): import necessary global functions and variables
(*2): _ENV = nil after this line the global environment is no longer accessible from the code. So, any attempt to add any variable to this environment will result in error. Any attempt to read from the global environment also will result in error. In Lua 5.1 setfenv function is used instead of manipulations with _ENV variable.
(*3): mess is not declared local, so in Lua 5.3 it will result in error. In older Lua it will be defined in a separate table.

This is one possible approach to create modules in Lua. Besides, there is strict.lua module serving similar purposes.