4

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"))

marcm
  • 43
  • 4
  • lhf and aschelper have posted different, but equally good, answers. Maybe they should be combined into one answer? – luther Dec 08 '19 at 01:00

3 Answers3

3
frepeat(helloworld("hello"))

will not pass the helloworld function like frepeat(helloworld) does, because it always means what it looks like: call helloworld once, then pass that result to frepeat.

You need to define a function doing what you want to pass that function. But an easy way to do that for a single-use function is a function expression:

frepeat( function () helloworld("hello") end )

Here the expression function () helloworld("hello") end results in a function with no name, whose body says to pass "hello" to helloworld each time the function is called.

aschepler
  • 70,891
  • 9
  • 107
  • 161
2

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
1

"repeat" is reserved word in lua. Try this:

function helloworld()
    print("hello world")
end
function frepeat(command)
    for i=1,10 do
        command()
    end
end
frepeat(helloworld)
An0ther0ne
  • 324
  • 3
  • 8
  • thank you for your quick reply, unfortunately I asked the wrong question and had to edit my question. I did however change the function name in my example. – marcm Dec 07 '19 at 18:19
  • @marcm Change question after answer not goog idea. But in you case solution is simple. Just replace "frepeat(helloworld)" to "frepeat(function() helloworld("hello") end)" as described in next answer from aschepler. – An0ther0ne Dec 07 '19 at 19:04