Declaring variables and scope question for Lua

lua, scope

Solution

There is no option to set this behavior, but there is a module 'strict' provided with the standard installation, which does exactly that (by modifying the meta-tables). Usage: require 'strict'

For more in-depth info and other solutions: http://lua-users.org/wiki/DetectingUndefinedVariables, but I recommend 'strict'.

Problem

I'm lead dev for Bitfighter, and we're using Lua as a scripting language to allow players to program their own custom robot ships. In Lua, you need not declare variables, and all variables default to global scope, unless declared otherwise. This leads to some problems. Take the following snippet, for example: ``` loc = bot:getLoc() items = bot:findItems(ShipType) -- Find a Ship minDist = 999999 found = false for indx, item in ipairs(items) do local d = loc:distSquared(item:getLoc()) if(d < minDist) then closestItem = item minDist = d end end if(closestItem != nil) then firingAngle = getFiringSolution(closestItem) end ``` In this snippet, if findItems() returns no candidates, then closestItem will still refer to whatever ship it found the last time around, and in the intervening time, that ship could have been killed. If the ship is killed, it no longer exists, and getFiringSolution() will fail. Did you spot the problem? Well, neither will my users. It's subtle, but with dramatic effect. One solution would be to require that all variables be declared, and for all variables to default to local scope. While that change would not make it impossible for programmers to refer to objects that no longer exist, it would make it more difficult to do so inadvertently. Is there any way to tell Lua to default all vars to local scope, and/or to require that they be declared? I know some other languages (e.g. Perl) have this option available. Thanks! Lots of good answers here, thanks! I've decided to go with a slightly modified version of the Lua 'strict' module. This seems to get me where I want to go, and I'll hack it a little to improve the messages and make them more appropriate for my particular context.

Original source