简体   繁体   English

如何在Lua中将函数作为参数传递?

[英]How to pass a function as a parameter in Lua?

Bit confused by all this; 有点困惑这一切; so here's what I am attempting to do! 所以这就是我想要做的! Have a def thus: 因此有一个def:

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: 在那个block_basic_DEF我希望传递init()函数的地址,这样在我的spawn中我可以做类似的事情:

params.startup() --ie actually call the original init function params.startup() - 实际上调用了原始的init函数

Lua functions are just values, and you can asssign them using their name without parens: Lua函数只是值,你可以使用他们的名字来设置它们而不用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. 它接近OOP,但实际上它就像函数是正常值一样简单。

If you wanted something more similar to a lambda, you have to spell out the whole function, omitting the name: 如果你想要一个更类似于lambda的东西,你必须拼出整个函数,省略名称:

startup = function() print("init") end

You just forgot the end keyword. 你刚忘了end关键字。 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? 你不会忽略C中的结束}吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM