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?

1
  • 1
    If you find yourself needing this, use a table indexed by the strings and with values the corresponding functions. Commented Feb 7, 2014 at 11:10

1 Answer 1

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.

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

3 Comments

Adding a note: the functions have to be global for this to work.
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
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.

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.