lua-users home
lua-l archive

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

You can try that:

function validate_table(t, default_value)
   -- Simply find the highest numerical index
   local maxn = 0
   for k,v in pairs(t) do
      if type(k)=="number" and k>maxn then
         maxn = k
   -- Then you fill holes with a default value
   for i=1,n do
      if t[i]==nil then
         if default_value==nil then
            -- If no default value defined just throw an error
            error("table contains nil")
            t[i] = default_value
   -- You can update table n so that array functions work
   table.setn(t, maxn)

I started Lua just a few weeks before 5.1 release, and I switched very early, so some things may not work with 5.0.

-----Message d'origine-----
De : [] De la part de David Given
Envoyé : 19 septembre 2006 05:47
À : Lua list
Objet : Arrays with holes in

I'm using Lua for this configuration language thingy. It tends to use constructs of the form:

a = b { foo, bar, baz }

...where b is a function that takes a table, and foo, bar and baz have been previously defined. This all works nicely.

However, if the user makes a typo:

a = b { foo, baar, baz }

...then things go wrong; baar evaluates to nil, which means that b() only sees the first item of the table.

I would like to be able to test for this.

Now, one of the problems with the faulty table is that because it has a nil element in it, it's not technically an array, which means I can't use table.getn(). (This is Lua 5.0.) What's the best way of testing to see if the table contains a nil element?

This is my current thought:

function validate_table(t)
	local i = 1
	while t[i] or t[i+1] do
		if not t[i] and t[i+1] then
			error("table contains nil!")
		i = i + 1

This should cause an error if the table contains a nil element followed by a non-nil element. It tests for the end of the table by finding two nil elements next to each other.

Any better suggestions?

+- David Given --McQ-+ "Is Eris true?" "Everthing is true." "Even false
|    | things?" "Even false things are true." "How can
| ( | that be?" "I don't know, man. I didn't do it!"
+- --+ --- _Prinicipa Discordia_