Is there a way to use i++
instead of i = i + 1
in Lua? I think it might be possible since Lua can use C functions directly.

- 8,029
- 10
- 53
- 79
-
4`++` is not a C function, it is an operator. So Lua being able to use C functions is not applicable. – Craig S. Anderson May 09 '15 at 09:36
-
Possible duplicate of http://stackoverflow.com/questions/7855525/simulate-in-lua-is-it-possible. – lhf May 09 '15 at 10:27
-
not necessarily - I'm curious whether there is any hacky way of achieving `i++` in Lua. Thanks anyway. `increment` function is a way around somehow – Mateusz Piotrowski May 09 '15 at 10:30
3 Answers
You'd have to modify the parser to accept ++
, since it's not part of the syntax. Creating a new incompatible dialect of Lua just to save a few characters just isn't worth it, though.
Defining some sort of a function for this won't work in general either, since functions in Lua are pass-by-value, so you'd have to write
i = incr(i)
which pretty much defeats the point, and doesn't let you express ++i
anyway.
Maybe you could do incr 'variableName'
and mess with the local environment of the calling function... but again, that's just overcomplicated, not worth the trouble and generally a horrible idea in every way imaginable.

- 3,113
- 16
- 20
If you want to avoid typing, see if your editor can expand ++i
to i = i + 1
for you.
If you just want a hacky way that doesn't involve modifying the Lua source code then tables will get you pass-by-reference and the __call
meta-method can be used as an expression or statement.
function num(v)
local t = {v or 0}
function postinc(t, i)
local old = t[1]
t[1] = t[1] + (i or 1)
return old
end
setmetatable(t, {__call=postinc})
return t
end
i = num()
print(i()) -- print(i++)
i() -- i++
print(i(0)) -- print(i)
Writing code like this is never worth it, accessing the "value" of i
now requires i(0)
.

- 6,151
- 1
- 21
- 28
While you can't do i++
or ++i
in Lua by default you can change i = i + 1
to i += 1
which is much better

- 21
- 3