使用Lua函数将参数传递给另一个带参数的函数。

这是我尝试做的原始想法。

function a(str)
    print(str)
end

function b(str)
    print(str)
end

function c(str)
    print(str)
end

function runfunctions(...)
    local lst = {...}
    lst.startup()
end

local n1 = a('1')
local n2 = b('2')
local n3 = c('3')

runfunctions(n3,n1,n2)

需要将几个函数作为参数传递给其他函数,并按顺序执行。一旦其中任何一个被执行,它就不能在几毫秒内再次执行,以便下一个函数可以被执行,以避免只执行其中几个函数而不运行到最后一个函数。

点赞
用户1009479
用户1009479

你需要闭包。

在你的代码中,函数 abc 都执行并且不返回任何东西。相反,返回一个执行操作的闭包(但现在不执行):

function a(str)
    return function() print(str) end
end

然后在需要时执行该函数:

function runfunctions(...)
    for _, v in ipairs{...} do
        v()
    end
end
2015-11-09 16:29:26
用户1847592
用户1847592
function runfunctions(...)
   for _, f_with_args in ipairs{...} do
      pcall((table.unpack or unpack)(f_with_args))
   end
end

runfunctions({c, '3'}, {a, '1'}, {b, '2'}, {print, "Hello", "world"})
function runfunctions(...)
   for _, f_with_args in ipairs{...} do
      pcall((table.unpack or unpack)(f_with_args))
   end
end

runfunctions({c, '3'}, {a, '1'}, {b, '2'}, {print, "Hello", "world"})

将给定的 Lua 代码添加了代码高亮,并翻译为中文。

2015-11-09 18:11:35