1

I have functions named

MapMSH(Msg.MSH, b)
MapPID(Msg.PID, b)
MapPV1(Msg.PV1,b)

NOW, in another function from where I will be calling above three functions, I have a variable u looping through values MSH, PID and PV1 I know I need to use .. operator to concatenate strings.

what I really want is the value in u to be concatenated to Map, something like

"Map"..u(Msg.u, b)   

so that my functions get called automatically as soon as the value in u matches. With the syntax above, it says unexpected symbol near "Map" Can someone please tell me the exact syntax for that?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
systemdebt
  • 4,589
  • 10
  • 55
  • 116
  • 1
    If you find yourself needing this, use a table indexed by the strings and with values the corresponding functions. – lhf Feb 07 '14 at 11:10

1 Answers1

2

Try this if your functions are in the global namespace.

funcList = {"MSH","PID","PV1"}

for _,u in pairs(funcList) do
    _G["Map"..u](Msg[u],"X")
end

Test

Msg = { MSH="MSH", PID="PID", PV1="PV1" }
function MapMSH(a, b)
    print( a..b )
end
function MapPID(a, b)
    print( a..b )
end
function MapPV1(a, b)
    print( a..b )
end

Output

MSHX
PIDX
PV1X

Your problem is very similar to this problem.

Community
  • 1
  • 1
Tim
  • 2,121
  • 2
  • 20
  • 30
  • Adding a note: the functions have to be global for this to work. – Yu Hao Feb 07 '14 at 10:58
  • for u in string.gmatch(S, "([^,%s]+)") do l[k] = u k=k+1 _G["Map"..u](Msg[u],R[1]) end but with this, it seem to pick only first one which is MSH and I want both the corresponding functions to be called at once if the list had MSH as well as PID and all three called if the list had MSH, PID and PV1 – systemdebt Feb 07 '14 at 11:19
  • The problem is that I want all three functions to be called in one go if there were 3 values passed in u and not one function per iteration of the loop. Secondly, i want the presence of the function to be checked as well because in case u had nil, then it will become Map.nil and function with that name obviously does not exist. – systemdebt Feb 07 '14 at 11:29