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!

2
  • 2
    Note that you can write table.key instead of table["key"].
    – lhf
    Commented Oct 21, 2011 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
    Commented Oct 21, 2011 at 22:19

1 Answer 1

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")
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.