News:

SMF - Just Installed!

Main Menu

New feature: use_strict()

Started by Stephen, December 29, 2012, 06:30:36 PM

Previous topic - Next topic

Stephen

It's been noted before that sometimes you can make simple mistakes in Lua code and they won't be caught. E.g.


local C = require("classic")
my_monster = kts.MonsterType {
   -- .....
   ai_avoid = all_open_pit_tiles   -- Mistake: should have been C.all_open_pit_tiles
}

function foo(x)
  print(xx)   -- Mistake: should have been 'x', not 'xx'
end

function bar(x)
  y = x + 2     -- Mistake: 'local' was forgotten (programmer meant to write 'local y = x + 2')
  print (y * 3)
end


The first of these (forgetting the "module prefix") is especially annoying (I've done it myself several times!).

Knights now includes a feature where you can request strict checking of global variables. To enable this, add "use_strict()" to the top of your module (below the "module(...)" line). If this is done, then any access to a global variable is an error, unless you have previously "declared" that variable (by assigning to it at the top level of the program). A full explanation is at http://www.knightsgame.org.uk/trac/wiki/lua/use_strict

This simple feature catches all three of the above mistakes.

If you want to try this out then here is a snapshot build:

http://www.solarflare.org.uk/snapshots/knights_2012_12_29.zip -- windows build
http://www.solarflare.org.uk/snapshots/knights_src_2012_12_29.tar.gz -- source code

Note that use_strict() is entirely optional. This means that existing modules will continue to work without modifications. However, I would recommend adding use_strict() to your modules if possible, since it will help catch common errors/bugs.