2

I'm very new to Lua, I'm working with it on an io controller which has strict limits on script sizes so I need to work within these limits.

I have a number of relays which I am controlling (1-64). I need to switch off a relay when an event happens, but the relay I'm switching off can change. I have a variable that holds the relay number and I need to turn off this relay.

I can achieve this using I statements:

if variable = 1 then
  io.relay1=0 //Turns off the relay
end
else if variable = 2 then
  io.relay2=0 //Turns off the relay
end

However, this will very quickly become a large script when repeated for the 64 relays. Is it possible to address the relay using the value of the variable as the relay name? Similar to the below:

io.relay{variable}=0 //Turns off the relay1/2/3/4/5 etc. depending on the value of variable

Alternatively, is there another way to keep the code compact?

2 Answers 2

3

Use

io["relay".. variable]=0 

However, this creates a string every time.

If you can change how io works, a better solution would be to make io.relay a table and then simply do io.relay[variable]=0.

Sign up to request clarification or add additional context in comments.

2 Comments

relays["relay"..tostring(variable)] = 0 - if variable is a nil
Absolutely spot on, thank you for your help. The io module is off the shelf, I have no control over the naming or structure of the addressing. Your suggestion works perfectly. Thank you
0

To avoid the string allocation issue that lhf's answer has, you could pre-generate a string table and index into that:

relay_names = {}
for k = 1,64 do
  relay_names[k] = "relay"..tostring(k)
end

Then setting the IO states would look something like this:

io[relay_names[1]] = 1

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.