lua-users home
lua-l archive

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


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:

==============================
#!/usr/bin/lua 

-- LEGAL GLOBALS BECAUSE THEY COME BEFORE METATABLE TWEAK
boisenberry = waterbury

do
	local mt = getmetatable(_G) or {}
	mt.__index = function(k,v)
		error("Global ".. tostring(v) .." does not exist", 2)
	end
	mt.__newindex = function(k,v)
		error("Cannot set global vars: ".. tostring(v), 2)
	end
	setmetatable(_G, mt)
end

-- COMMENT OUT ONE OF THE PRECEDING TO TEST READ OR WRITE OF A GLOBAL
strawberry = 4
strawberry = blueberry
==============================

Just to make it more memorable, I put it in a function called use_strict():
==============================
local function use_strict()
	local mt = getmetatable(_G) or {}
	mt.__index = function(k,v)
		error("Global ".. tostring(v) .." does not exist", 2)
	end
	mt.__newindex = function(k,v)
		error("Cannot set global vars: ".. tostring(v), 2)
	end
	setmetatable(_G, mt)
end
==============================

Axel, you have no idea how much work you've saved me with this suggestion. I'm 
very careless with typing, so it will save me hours and hours of debugging.

Just yesterday I was reminiscing about the "use strict" of my Perl youth, and 
wishing Lua had it. Today you showed me Lua DOES have it.

Thanks!

SteveT

Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt