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
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.
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.
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.
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 .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With