lualua-5.1defold

Run a string as lua code to call a function with only the function name


I am making a dynamic callback table for a helper function that handles input events. I want to make a(testString) execute when functionTable[1](testString) executes or allow a way for it to be run directly from a string.

functionTable = {}
testString = "atad atad atad"

function a(param)
    print(param)
end

functionTable[1] = "a"

exec(functionTable[1].."(testString)")

How should I be doing this?

(for Lua 5.1)


Solution

  • you can use the load() function to execute strings:

    functionTable = {}
    testString = "atad atad atad"
    
    function a(param)
        print("hello " .. param)
    end
    
    functionTable[1] = "a"
    
    load(functionTable[1].."(testString)")()