Craig S
Craig S

Reputation: 1

Passing variable names to functions

I have an application and some code that works but I want to make it a callable function such as :-

tankFunction("tank1") so that the below function (which works) would be able to work for any tank as per the entered parameter "tank1" or "tank2" or "tank3" and so on..

So basically each variable contained in the existing function would represent the enter parameter:

tank1CoolManCtrlOn = reg.tank1CoolManCtrlOn 

Currently, the two above variables are coded just for "tank1", if "tank2" were passed into tankfucntion such as tankfunction("tank2") then the variables would need to be:

tank2CoolManCtrlOn = reg.tank2CoolManCtrlOn

So the variables would be ####CoolManCtrlon = reg.####CoolManCtrlOn where the #### is where the parameter needs to be entered.

Once these variables are created they then need to be passed to the tank() function and the returned values need to be then set to the output registers.

function tank1Function()  
--Tank1 - Start
--This is the Control Function Block Call for - Tank1

--Below is where each variable is set for the function block call.
tank1CoolManCtrlOn = reg.tank1CoolManCtrlOn
tank1CoolManCtrlOff = reg.tank1CoolManCtrlOff
tank1HeatManCtrlOn = reg.tank1HeatManCtrlOn
tank1HeatManCtrlOff = reg.tank1HeatManCtrlOff
tank1PV = reg.tank1PV
tank1SV = reg.tank1SV
tank1Debounce = reg.tank1Debounce
tank1Hysteresis = reg.tank1Hysteresis
tank1LowAlm = reg.tank1LowAlm
tank1HighAlm = reg.tank1HighAlm
tank1CoolManIND = reg.tank1CoolManIND
tank1HeatManIND = reg.tank1HeatManIND
tank1Mode = reg.tank1Mode
tank1CTRLType = reg.tank1CTRLType

--This is the function block call for Tank1 where each parameter is set.
 tank1CoolManIND1, tank1HeatManIND1, tank1CoolManCtrlOn1,
 tank1CoolManCtrlOff1, tank1HeatManCtrlOn1, tank1HeatManCtrlOff1  = 
 tank(tank1CoolManCtrlOn, tank1CoolManCtrlOff, tank1HeatManCtrlOn, 
 tank1HeatManCtrlOff, tank1PV, tank1SV, tank1Debounce, tank1Hysteresis, 
 tank1LowAlm, tank1HighAlm, tank1CoolManIND, tank1HeatManIND, tank1Mode, 
 tank1CTRLType) 

 --This is where the results of the function block set the required  
 --Variables.
 reg.tank1CoolManIND = tank1CoolManIND1
 reg.tank1HeatManIND = tank1HeatManIND1
 reg.tank1CoolManCtrlOn = tank1CoolManCtrlOn1 
 reg.tank1CoolManCtrlOff =  tank1CoolManCtrlOff1
 reg.tank1HeatManCtrlOn =  tank1HeatManCtrlOn1
 reg.tank1HeatManCtrlOff = tank1HeatManCtrlOff1
--Tank1 - End  

 end

Upvotes: 0

Views: 139

Answers (1)

luther
luther

Reputation: 5544

Your variable names have a lot of repetition, which means you could easily represent your tanks in nested tables.

local tanks = {{}, {}, {}}
local reg = {tanks = {{}, {}, {}}}

local function tank(t)
  return {
    -- Calculate fields from t.
  }
end

local function tankFunction(i)
  tanks[i] = reg.tanks[i]
  reg.tanks[i] = tank(tanks[i])
end

tankFunction(1)

The tank tables would have keys such as PV, SV, and Debounce.

Upvotes: 3

Related Questions