Lua seems very verbose. Why isn't it like C?

The compactness of C (and the Unix environment in which it grew up) comes from the technical limitations of very clunky teleprinters. Now we have tab completion and smart editors which can do abbreviations, so it doesn't really take more time to type Lua than C. For example, in SciTE one can add this to the abbreviations file:

if = if | then \n \
 \n \
end

Typing 'if' followed by ctrl-B will then put out the expanded text, properly indented.

Another point is that we spend much more time reading code than writing code, so the question is really whether it reads well. C is very readable to someone who is used to reading C, but Lua is more readable for casual programmers.

A C-like Lua derivative is Squirrel.

There is one important sense that Lua is the C of dynamic languages; it is small, fast, and only comes with the essential batteries. This is more than an analogy, since the Lua implementation only uses what is available with the C89 libraries.

1.5.1 Why do Lua arrays count from one?

Oddly, the thing that really gets some people overexcited is that in Lua array indices count from one.

In mathematical notation array indices count from one, and so does Lua. In other words, they are not offsets.

The historical reason (see The Evolution of Lua) is that Lua evolved to solve engineering needs at the Brazillian state oil company (Petrobras). It was designed for engineers who were not professional programmers and more likely to be used to FORTRAN.

You can make your arrays start with zero, but the standard library functions (such as table.concat) will not recognise the zeroth entry. And # will return the size minus one.

t = {[0]=0,10,20,30} -- table constructor is a little clunky for i = 0,#t do print(i,t[i]) end -- not 0,#t-1 !

1.5.2 Can I use a conditional expression like "x ? y : b" in C?

The Lua form is res = x and y or b which works because the value of these operators is not just a boolean value, but is their second operand. Proper short-circuiting takes place, that is the expression b will not be evaluated if the condition was true.

But please note the case where y is either nil or false. The first and fails and we pick up b anyway.

Multiple values are understood:

> print (false and 5 or 10,'hello')
10 hello

People will often write a convenience function:

function choose(cond,a,b)
 if cond then return a else return b end end

This evaluates both values first, so it is suitable only for simple values, but it is bulletproof.



Back