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
      end
   end
   -- 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")
         else
            t[i] = default_value
         end
      end
   end
   -- You can update table n so that array functions work
   table.setn(t, maxn)
end

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 : lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] 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!")
		end
		i = i + 1
	end
end

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
|  dg@cowlark.com    | things?" "Even false things are true." "How can
| (dg@tao-group.com) | that be?" "I don't know, man. I didn't do it!"
+- www.cowlark.com --+ --- _Prinicipa Discordia_