How to Use “strict.lua”

strict.lua is a script included in the Lua 5.1.4/5.1.5 distribution package, and through its use, errors due to global variable typos can be prevented, to some extent.

strict.lua

strict.lua is called from the Lua script by require and used. With the Lua script that requires strict.lua, errors will be caused in the following cases.

  • When attempting to reference a global variable for which the value is un-configured
  • When attempting to configure the value of the first global variable within a function.

When using strict.lua, it will be possible to regard configuring values for global variables in the main chunks outside of all of the functions as “declaration of global variables.” If you try to use an undeclared global variable, since strict.lua will cause an error, it is become possible to detect when you are attempting to use a mistaken global variable with a typo.

[When strict.lua is not used]

print(a)       -- 'a’ is first displayed' It will be displayed as “nil”.
function f() 
  b = 2        -- Substitute value in global variable within function for the first time 
end
f()            -- 2 is substituted for b

[When strict.lua is used]

require "strict" 
print(a)       -- 'a’ is the first appearing variable, so error
require "strict"
function f() 
  b = 2        -- error because a value is substituted for global variable for the first time within the function
end
f()            -- halt due to error

With strict.lua, because errors are first detected when attempting to execute code, errors in unexecuted parts when tests are conducted cannot be detected. You will need to devise test cases to execute all of the code.

Additionally strict.lua manipulates the _G global variable’s meta table. For this reason, there is a possibility that it will not work well by butting with the other libraries that operate the meta table of _G.

Return to Top