Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate += in Lua, is it possible?

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!

like image 753
Josh Avatar asked Oct 21 '11 21:10

Josh


1 Answers

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")
like image 185
lhf Avatar answered Sep 29 '22 10:09

lhf