1. We have added a Gift Upgrades feature that allows you to gift an account upgrade to another member, just in time for the holiday season. You can see the gift option when going to the Account Upgrades screen, or on any user profile screen.
    Dismiss Notice

Calling a function from a string variable

Discussion in 'Civ5 - SDK / LUA' started by whoward69, Apr 9, 2016.

  1. whoward69

    whoward69 DLL Minion

    Joined:
    May 30, 2011
    Messages:
    8,518
    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!
     
  2. whoward69

    whoward69 DLL Minion

    Joined:
    May 30, 2011
    Messages:
    8,518
    Location:
    Near Portsmouth, UK
    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
    
     

Share This Page