Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua function with arg pass to another function with arg

Tags:

function

lua

Here is raw idea of what I'm trying to do.

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)

Few functions got to be pass as args to other functions and being executed in sequence. Once any of them been executed it can't be executed for msec so next will be executed, to avoid only being executed few of them and don't run till the last one.

like image 970
user1768615 Avatar asked Sep 05 '26 10:09

user1768615


1 Answers

You need closures.

In your code, the functions a, b and c all do the execution and returns nothing. Instead, return a closure that does the work (but not execute for now):

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

Then execute the function when needed:

function runfunctions(...)
    for _, v in ipairs{...} do
        v()
    end
end
like image 89
Yu Hao Avatar answered Sep 08 '26 23:09

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!