1

just messing around in computercraft, trying to use a function as an argument but cant get it to work

bla = function() print("bla") end
execfunc = function(func) func() end
execfunc(bla())

I would like to do something as seen above, but with working code and not this nonsense

user3837761
  • 17
  • 1
  • 2

3 Answers3

7

Drop the () from the argument to execfunc. You want to pass bla to execfunc not the result of calling bla().

> bla = function() return "bla" end
> execfunc = function(func) print(type(func)) end
> execfunc(bla())
string
> execfunc(bla)
function
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
0

You've got it right on the formal parameter side: Use the function call operator () on the expression func. If the value of the expression is actually a function, it'll be called; If not, Lua will throw an error.

On the actual argument side, you have a mistake. To pass an argument, simply put an expression in the argument list. You want to pass the value in the variable bla so execfunc(bla). The fact that the expression is simply a variable and the value in the variable is a function value doesn't change anything.

Lua variables are dynamically typed. The compiler doesn't keep track of which variables would be last assigned function values before they are used. In fact, it can't. You could write a function that sometimes returns a function and sometimes returns a number. In either case, you can still try to call the result.

local f = function () 
    if Wednesday then 
        return 7 
    else 
        return function (n) return n + 1 end
    end
end

local g = f()
g() -- is the value in g a function or not? It doesn't matter to the compiler.
Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
0

The way that you get your function raw without calling it is not using parenthesis ( )

local function a()
  print("AAA")
end

local function b(func)
   func()
end

b(a)
-- Output:
-- AAA

and for your case:

...
execfunc(bla)
-- Everything was fine except the parenthesis for your function (bla)
111WARLOCK111
  • 153
  • 1
  • 1
  • 9