Variable Declaration and Area Question for Lua

I head dev for Bitfighter , and we use Lua as a scripting language to allow players to program their own robotic ships.

In Lua, you do not need to declare variables, and all variables are global by default, unless otherwise specified. 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 fragment, if findItems () does not return any candidates, then closestItem will still refer to the last ship it found, and in the meantime this ship could be killed. If the ship is killed, it no longer exists, and getFiringSolution () will fail.

Did you notice a problem? Well, my users too. It is subtle, but with a dramatic effect.

, - . , , .

Lua vars / , ? , (, Perl) .

!


, !

Lua "strict". , , , , .

+5
4
+3

.

Lua , -, globals _G ( , Lua AFAIK). Lua, __newindex metatable _G, . __newindex , , - : , , ..

_G, setfenv. . .

+2

, , GC . , , , "" - . , , , .

, , sandbox, , script. ( ) .

, . , , , .

, , , , , , .

-- table of globals that will available to user scripts
local user_G = {
        print=_G.print,
        math=_G.math,
        -- ...
    }
-- metatable for user sandbox
local env_mt = { __index=user_G }


-- call the function in a sandbox with an environment in which new global 
-- variables can be created and modified but they will be discarded when the 
-- user code completes.
function doUserCode(user_code, ...)
    local env = setmetatable({}, env_mt) -- create a fresh user environment with RO globals
    setfenv(user_code, env)        -- hang it on the user code
    local results = {pcall(user_code, ...)}
    setfenv(user_code,{})
    return unpack(results)
end

, , , .

, , , ( ) ( ) . Lua, .

0

All Articles