lua-users home
lua-l archive

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


2015-08-27 5:59 GMT+02:00 Nan Xiao <xiaonan830818@gmail.com>:

> Sorry, I am a little confused. If possible, could you spare a little time to
> explain the  relationship among chunk, statement and expression?

In simplest but not most exact terms, it is a question of size
and of what Lua does to them.

Expression is the smallest of the three. It defines the operations
needed to construct a value. E.g. `2+2`. Lua "evaluates"
an expression.

Next comes a statement. It may contain expressions, but it must
also say what to do with the values they define. E.g. `a=2+2`.
Lua "executes" a statement.

Biggest is a chunk. It can consist of many statements. E.g.
`a=2+2; b=10*a`. Lua "compiles" or "loads" a chunk.

In somewhat more exact terms:
- An expression can actually define a list of any number of
values. You can make that exactly one value by putting
parentheses around it.
- A statement stops when there is no way that including
any of the code that follows it would make sense. You can
always force it to stop by giving a semicolon, but it is not
necessary. An expression by itself is usually not a valid
statement, except when it is a function call.
- The smallest possible chunk is empty. One statement is
always a valid chunk, but a chunk is not always a valid
statement. You can put `do` ... `end`around a chunk to turn
it into a valid statement.

The biggest difference between statements and chunks
has to do with compiling and running code. Lua is an
interpreted language: it can compile chunks and store
them as functions in between doing other calculations.
A chunk is whatever you want to have compiled.

The syntactic sugar that makes it look like C or Pascal
is a little misleading. When you write

function f(x,y) return 10*x+y end

this is a statement which requests immediate compilation
of a chunk. It can be written in several other ways that use
less syntactic sugar.

f = function(x,y) return 10*x+y end

function f(...) local x,y=...; return 10*x+y end

f = load"local x,y=...; return 10*x+y"

The last of these is not quite equivalent to the others
when some of the names are not local. However, it
illustrates the difference between expressions, statements
and chunks most clearly.

- Everything inside the string passed to `load` is
a chunk.
- The chunk consists of two statements.
- Inside the statements are expressions `...` and
`10*x+y`.
- The call to `load` is an expression which returns
a value of type 'function'.
- The assignment of that value to `f` is a statement.
- That whole statement is a chunk when you type it
in to the Lua interpreter, which will generate the code
for it and execute that code.