[SOLVED] Avoiding callback hell
Posted: Mon Feb 04, 2019 7:38 pm
Hi, I'm currently working on an RPG where I have scripted sequences and I have code executing one after another and the way I'm dealing with it is using callbacks, which in retrospect wasn't the best way to deal with it, this is how it looks now:
Is there a way to make avoid this? is there a solution like Promises or async/await in javascript?
I did found this library by airstruck, which he added to knife (the knife one works diferently than the one in the post), but I find it verbose and overcomplicated.
There has to be a way (maybe using coroutines) to write easy asynchronous code in Lua.
Thanks in advance!
UPDATE:
Well, it didn't took me much time to find a solution, it was coroutines! sorry for the pointless post.
I manage to make this simple function:
So now my code now looks like this:
Which is probably the closest thing I'm going to get to write readable asynchronous code.
So I guess it's solved? I'll just leave this here for anyone having the same problem.
Code: Select all
timer:after(3, function()
textBox:write("Hi")
textBox:write("wats up", function()
moveNpcRight()
timer:after(5, function()
stopNpc()
textBox:write("I just moved to the right", function()
...
end)
end)
end)
end)
I did found this library by airstruck, which he added to knife (the knife one works diferently than the one in the post), but I find it verbose and overcomplicated.
There has to be a way (maybe using coroutines) to write easy asynchronous code in Lua.
Thanks in advance!
UPDATE:
Well, it didn't took me much time to find a solution, it was coroutines! sorry for the pointless post.
I manage to make this simple function:
Code: Select all
function async(f)
local co = coroutine.wrap(f)
co(coroutine.yield, co)
end
Code: Select all
async(function(wait, cont)
timer:after(3, cont) wait()
textBox:write("Hi")
textBox:write("wats up", cont) wait()
moveNpcRight()
timer:after(5, cont) wait()
stopNpc()
textBox:write("I just moved to the right", cont) wait()
...
end)
So I guess it's solved? I'll just leave this here for anyone having the same problem.