lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 18 February 2011 20:32, Steve Litt <slitt@troubleshooters.com> wrote:
> On Friday 18 February 2011 08:53:25 Axel Kittenberger wrote:
>> > BTW, is there a tool that can parse a Lua script to spot syntax
>> > errors?
>>
>> Best is to add a metatable to globals _G that errors on index. Put
>> this on top of your program.
>>
>> do
>>   local mt = getmetatable(_G) or {}
>>   mt.__index = function(k) error("Global "..k.." does not exist", 2) end
>>   setmetatable(_G, mt)
>> end
>
> Axel,
>
> This is wonderful. It's like "use strict" for Lua. However, I had a problem
> with your code because k was always a table, regardless of the global I read
> or wrote (I also added a __newindex() to catch writes to globals). So I
> changed your code to add a v to the __index() and __newindex() args, and it
> seems now to do what you intended:

__index and __newindex always receive the table as the first argument
(see http://www.lua.org/manual/5.1/manual.html#2.8 and
http://www.lua.org/pil/13.4.1.html ). So the correct signature should
be:

mt.__index = function (t,k) error("Global "..k.." does not exist", 2) end
mt.__newindex = function(t,k,v) error("Cannot set gloval var "..k.."
to "..tostring(v), 2) end