luacomputercraft

How or Can I pass a function with argument as a parameter to a function in lua?


I am not running straight lua but the CC-Tweaks ComputerCraft version. This is an example of what I am trying to accomplish. It does not work as is.

*edited. I got a function to pass, but not one with arguments of its own.

function helloworld(arg)

    print(arg)

end

function frepeat(command)

    for i=1,10 do

        command()

    end

end

frepeat(helloworld("hello"))


Solution

  • Try this code:

    function helloworld(arg)
        print(arg)
    end
    
    function frepeat(command,arg)
        for i=1,10 do
            command(arg)
        end
    end
    
    frepeat(helloworld,"hello")
    

    If you need multiple arguments, use ... instead of arg.