lua-users home
lua-l archive

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

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_

Attachment: signature.asc
Description: OpenPGP digital signature