lua-users home
lua-l archive

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


On Thu, 2008-03-27 at 12:17 -0700, Lua Newbie wrote:
> I've googled and searched the archive to no avail ...
> 
> Is there a way to detect duplicate field names in a table?
> 
> Suppose I want users to be able to configure an app using lua.  They
> create a table like:
> 
> config={key1=val1,key2=val2}
> 
> I want to detect and reject any duplicate keys (eg key1=key2).  By
> default, Lua appears to ignore all but the last instance of the key.
> (I'm guessing that it actually installs val1 at key1 but then replaces
> val1 with val2.)  That is OK in some cases, but I've got lots of keys
> and want to detect typos that lead to duplicates.

You are correct.  You can only have one value with a given key.  I can't
think of a way of detecting and warning against this using the syntax
you are using without modifying the compiler.  However, you could adjust
the syntax of your configuration file so that you can detect it
yourself.  Perhaps something like this?

	key1 { "val1" }
	key2 { 2 }
	key3 { true }

You'd need to create a function for each "key", or if you had many of
them, or you didn't know in advance what the keys may be, you can set up
a meta table on the function environment table you execute your
configuration script in to handle them.

An example might be (untested, possibly not the best solution, doesn't
do the checking you want, unsafe assumptions, etc, etc)

local conf = loadstring(... string containing configuration ...)
local env = { }

setmetatable(env, { __index = function(t, keyname)
	return function(values)
		print(keyname, "=", values[1])
	end
end })

setfenv(conf, env)
conf()

This prints the following here:

key1    =       val1
key2    =       2
key3    =       true

>From the function that prints out what's passed, you could check if the
configuration key has already been set, do sanity checking on it, and
insert the value into some table invisible to the configuration script.

B.