Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a parameter in Lua?

Tags:

function

lua

Bit confused by all this; so here's what I am attempting to do! Have a def thus:

block_basic_DEF =
{
    image = "button.png",
    name = "basic block",
    obj_table = this_obj_table.common_objects_table,
    startup = function() init(), <----- This is the problem
}

In another file I access as one would expect with:

function spawn(params)
    local obj = display.newImage(params.image)
    -- etc.

In that block_basic_DEF I wish to pass the address of the init() function such that in my spawn I can do something like:

params.startup() --i.e. actually call the original init function

like image 381
Mark Hula Avatar asked Jun 07 '13 12:06

Mark Hula


People also ask

Can you pass a function as a parameter?

Passing a function as parameter to another functionC++ has two ways to pass a function as a parameter. As you see, you can use either operation() or operation2() to give the same result.

How do you pass arguments in Lua?

To pass arguments into Lua, the script name and arguments must be enclosed within double quotes. The arguments are stored within the arg variable in Lua, which is a table of strings.

How do you call a function in Lua?

The API protocol to call a function is simple: First, you push the function to be called; second, you push the arguments to the call; then you use lua_pcall to do the actual call; finally, you pop the results from the stack.

What does 3 dots mean in Lua?

The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .


2 Answers

Lua functions are just values, and you can asssign them using their name without parens:

function init() 
     print("init");
end

block = { 
     startup = init
}

And then call it like a regular function

block.startup()

It is near to OOP, but in fact it's as simple as the fact that a function is a normal value.

If you wanted something more similar to a lambda, you have to spell out the whole function, omitting the name:

startup = function() print("init") end
like image 138
Bartek Banachewicz Avatar answered Sep 18 '22 06:09

Bartek Banachewicz


You just forgot the end keyword. It is part of a function definition and you can not leave it out. You wouldn't leave out the closing } in C either right?

block_basic_DEF =
{
    image = "button.png",
    name = "basic block",
    obj_table = this_obj_table.common_objects_table,
    startup = function() init() end, -- <-- This was the problem
}

Apart form that, the following two syntax variations are equal:

function foo()
end

foo = function()
end
like image 29
dualed Avatar answered Sep 18 '22 06:09

dualed