1

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.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79

3 Answers3

5

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.

Staven
  • 3,113
  • 16
  • 20
4

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).

ryanpattison
  • 6,151
  • 1
  • 21
  • 28
2

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

tomsterBG
  • 21
  • 3