Running a LUA script one part at a time

Started by
2 comments, last by Endurion 11 years, 4 months ago
Hiya, I have some experience writing my own scripting languages in the past, but wanted to have a go at using LUA for a little 2d rpg type game.

It was very easy to get it loading a script and running it within the game, so far so good. smile.png

Next stage is, instead of running an entire script at once (via lua_pcall), I want to be able to run through a script, up until it reaches certain time consuming functions, when I want to pause the script until the c++ tells it to resume again.

Here's the flow:

monster.lua:


TextOut("Hello I am a monster")
Wait(5)
TextOut("Now I'm going to eat you")
Wait(2)
MoveToPlayer()
TextOut("Yum yum")


So within most scripts run by characters etc, I need to pause the script, get on with running the rest of the game, other scripts etc, then resume again when the wait condition is satisfied.

The example above has 2 'waiting' functions, Wait (number of seconds), and MoveToPlayer (which may take a varying amount of time).

Hopefully this should make sense.

Does anyone have any idea how I should achieve this in lua? I'm having inkling feelings it may be to do with the yield and resume commands, but I haven't seen any decent explanations.

Many thanks.
Advertisement
Pseudo code, you must polish it...


Lua code
function taskA()
TextOut("Hello I am a monster")
Wait("A", 5)
TextOut("Now I'm going to eat you")
Wait("A", 2)
MoveToPlayer()
TextOut("Yum yum")
end
function Wait(what, period)
CppWait(what, period)
coroutine.yield()
end
function resumeA()
coroutine.resume(coA)
end
-- main code
coA = coroutine.create(taskA)

C++ code
void CppWait(std::string what, int period)
{
// add period to some condition list by "what"
}
void YourGameLoop()
{
if(condition for taskA is met) {
callLuaCode(resumeA);
}
}


Hope the code explains itself.
Note: I never used Lua coroutine before...

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

Ahha! biggrin.png

Thanks wqking, that seems to make a lot more sense.

I thought it should be able to do it, just wasn't sure of the syntax. Surprising that I couldn't find more tutorials on this, as it's such a basic necessity for scripting in a game. But maybe I just didn't know what to google for before.
Also a hint: You can return a value to C via yield and pass a parameter in via resume. This may come in handy for the Wait function.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

This topic is closed to new replies.

Advertisement