19

Someone had told me about overloading the operators, but I'm not even sure how I would begin to do that. What I'm attempting to do is change:

table["key"]=table["key"]+12345

into

table["key"]+=12345

Or even using a function, that would be wonderful. I've searched, but can't find an answer, so I'm hoping someone here can direct me to the source or be able to answer the question directly. If doing the longhand form of it is ultimately going to be the shortest way to do it, then I suppose I'll stick with that. I'm just trying to save as many keystrokes as possible, since I do have hundreds of places where this would be implemented. Thanks!

Josh
  • 3,225
  • 7
  • 30
  • 44
  • 2
    Note that you can write `table.key` instead of `table["key"]`. – lhf Oct 21 '11 at 21:43
  • 3
    Generally if you want to add a value to a variable Lua, you just do it longhand. e.g. `var = var + value`. You could roll your own function to do it, but you're not going to save yourself much typing. – Alex Oct 21 '11 at 22:19

1 Answers1

15

You want this?

function increment(t,k,v)
   t[k]=t[k]+(v or 1)
end

Use it as follows:

increment(table,"key",12345)

or, if you want to increment by 1, simply as

increment(table,"key")
lhf
  • 70,581
  • 9
  • 108
  • 149