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 <> 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 and ). So the correct signature should

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