Why Lua Does Not Allow i += 1, i *= 2, etc

In Lua you cannot write code like this:

i = 0
i += 1

You get a syntax error. Instead you must write:

i = 0
i = i + 1

Friends have asked me before why this is this case, so today I want to explain the reasoning behind this seemingly odd limitation.

Statements Versus Expressions

The Lua manual distinguishes between statements and expressions. Statements include blocks, control structures, and most importantly for this article, assignment. In other words, i = 0 is a statement.

Expressions can be numbers, strings, function definitions, table constructors, function calls, and a few other things. f(i) is an example of an expression.

Here is the important part: expressions can contain other expressions. If you think about it for a second, this is obvious. Function calls are expressions and Lua lets us write f(g(), h()), so clearly we can nest expressions. But we cannot nest statements in the same way. Furthermore, we cannot mix expressions with assignment statements unless the expression is on the right-hand side.

This is key. It is why we can write i = i + 1, which is an assignment statement but has the expression i + 1. But you may rightfully wonder, “Why can’t Lua transform i += 1 into that code?” The answer lies in the details of metamethods.

Metamethod Trickiness

Let’s say that i is a table with an __add metamethod—maybe it’s an implementation of a 2D vector class. If we allow the code i += 2 then how many times should we invoke that metamethod? Once because i appears only once? Or twice because in effect we are writing i = i + 2? Lua dodges this issue by forcing us to write the explicit form.


I know this isn’t the most informative article, and frankly I might even be incorrect in my reasoning. But I hope it helps give some insight when Lua does not provide what seems to be such an obvious feature to many programmers.


Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s