Calling a function from a string variable

whoward69

DLL Minion
Joined
May 30, 2011
Messages
8,713
Location
Near Portsmouth, UK
Just thought I'd throw this out there (partly so when I next search for the answer, Google will find it!)

Given a function abc
Code:
function abc(iData1, iData2)
    return string.format("Data1=%i, Data2=%i", iData1, iData2);
end

and some data values
Code:
local i1 = 40
local i2 = 60

we can call it
Code:
print(abc(i1, i2))
and get the expected output
Code:
Data1=40, Data2=60

But we can also put the name of the function into a variable
Code:
local xyz = "abc"
execute the function based on the contents of the variable
Code:
print(loadstring("return " .. xyz .. "(...)")(i1, i2))
and also get the expected output
Code:
Data1=40, Data2=60

Enjoy!
 
The loadstring() needs to be wrapped in a pcall(), otherwise errors in the called function (whatever's in xyz) will be silently ignored.

Code:
local status, ret = pcall(function () return loadstring("return " .. xyz .. "(...)")(i1, i2) end)
if (status) then
    print(ret)
end
 
Top Bottom