简体   繁体   English

如何在Lua中正确地重新分配变量?

[英]How do I properly reassign variables in Lua?

I am writing a user program for a simulation software. 我正在编写用于仿真软件的用户程序。 There is a variable called adj_elect05. 有一个名为adj_elect05的变量。 The following chunk of code gets called over and over again. 下面的代码块被一遍又一遍地调用。 Each time it gets called, I want adj_elect05 (which has a numeric value) to be incremented by a certain amount, and then have that amount written to a file. 每次调用它时,我都希望adj_elect05(具有数字值)增加一定量,然后将该量写入文件中。 This is the code that works: 这是有效的代码:

increment = -10

adj_elect05 = adj_elect05 + increment

oct_voltages = io.open(O_V, "a+")
oct_voltages:write("\n", adj_elect05) 
oct_voltages:close ()

In the file I get a list of numbers: -10, -20, -30, and so on. 在文件中,我得到一个数字列表:-10,-20,-30,依此类推。 The problem is I need to give adj_elect05 a generic name so that it can be changed later on without having to change every instance it shows up so I wrote: 问题是我需要给adj_elect05一个通用名称,以便以后可以更改它而不必更改它显示的每个实例,所以我写道:

increment = -10
octupole_v = adj_elect05

octupole_v = octupole_v + increment

oct_voltages = io.open(O_V, "a+")
oct_voltages:write("\n", octupole_v) 
oct_voltages:close ()

With this, I get -10 written to the file for ever time the code runs, rather than having it decrease by ten every time. 这样,每次代码运行时,我都会将-10写入文件,而不是每次减少10。 What am I doing wrong? 我究竟做错了什么?

What you need is to use local variable: 您需要使用局部变量:

local increment = -10
local octupole_v = adj_elect05
octupole_v = octupole_v + increment

By default variables are considered global (unlike Python). 默认情况下,变量被视为全局变量(与Python不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM