在Lua中模拟+ =,可以吗? [英] Simulate += in Lua, is it possible?

查看:103
本文介绍了在Lua中模拟+ =,可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我要重载运算符,但是我什至不确定如何开始这样做.我试图做的是改变:

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

进入

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!

推荐答案

您想要这个吗?

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

按以下方式使用它:

increment(table,"key",12345)

或者,如果您想增加1,则简单地设置为

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

increment(table,"key")

这篇关于在Lua中模拟+ =,可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆