lua-users home
lua-l archive

Re: Say No to global-by-default

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


It was thus said that the Great Axel Kittenberger once stated:
> 
> And yes this applies to config files as well. I used Lua like this and got
> negative feedback of people complaining there wasn't any notification
> because they misspelled a variable. So instead after the user config file
> finished, I made a loop that checks if any unknown variables are in global
> space and error if so.
 For this use case, I think it would be easier to do this:
	CONF =
	{
	 host = "localhost",
	 port = 8080,
	 datadir = '/tmp',
	 syslog =
	 {
	 id = 'my-daemon',
	 facility = 'local1',
	 },
	}
	setmetatable(CONF,{
	 __newindex = function(_,key)
	 error(string.format("invalid config parameter: %s",key),2)
	 end
	})
	f = loadfile(arg[1] or "config.txt","t",CONF)
	okay,err = pcall(f)
	if not okay then print(err) end
 You can set default values, and you get error checking:
	[spc]lucy:/tmp/bar>lua-53 read.lua 
	config.txt:2: invalid config parameter: plort
	[spc]lucy:/tmp/bar>
	[spc]lucy:/tmp/bar>lua-53 read.lua 
	config.txt:5: attempt to index a nil value (global 'sylog')
	[spc]lucy:/tmp/bar>
 -spc

AltStyle によって変換されたページ (->オリジナル) /