use_strict

Name

use_strict – enable strict checking of global variable usage

Synopsis

-- Place this at the top of init.lua
-- (directly after mod.RegisterMod)
use_strict()

Description

use_strict() enables a mode where all usage of Lua global variables is strictly checked. If a global variable is used before it is first assigned to, or if the first assignment to a global variable occurs anywhere other than the main chunk's top level, then an error message will result.

The intention of this is to catch mistakes where a global variable name is misspelled. For example, if I write to a global variable named floor_tile, but then later refer to it as floot_tile (a typo), then in standard Lua, this would not result in an error message; instead, a value nil would be used for floot_tile. This might cause an error, or it might just create a subtle bug that takes a long time to debug, depending on what the code is actually doing with that variable. By enabling use_strict(), the typo can be found much sooner.

Return Value

None.

Errors

use_strict() itself doesn't throw any errors. After use_strict() returns, errors may be raised by global variable accesses, as described above.

Notes

If you do actually want to use a global variable with a default value of nil, then you will need to explicitly assign to that variable first, before using it. This can be achieved easily enough, by writing something like my_variable = nil near the top of your code. Then, uses of my_variable will not be classed as errors, because my_variable has previously been assigned to (even though the assigned value was only nil). The base module uses this technique with a variable called Dsetup: see dungeon_setup.lua.

Examples

The base module uses use_strict() in its init.lua.

Here are some code examples that might make the use_strict errors clearer:

use_strict()

g1 = "hello"        -- Valid, creates new global variable
kts.DebugPrint(g1)  -- Valid, uses global variable declared above
kts.DebugPrint(g2)  -- Error, "g2" hasn't been declared yet

if something() then
    g3 = "goodbye"  -- Error, new global "g3" can only be declared at top level,
                    -- not within an "if"
end

See Also

mod.RegisterMod