Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua task scheduling

Tags:

lua

I've been writing some scripts for a game, the scripts are written in Lua. One of the requirements the game has is that the Update method in your lua script (which is called every frame) may take no longer than about 2-3 milliseconds to run, if it does the game just hangs.

I solved this problem with coroutines, all I have to do is call Multitasking.RunTask(SomeFunction) and then the task runs as a coroutine, I then have to scatter Multitasking.Yield() throughout my code, which checks how long the task has been running for, and if it's over 2 ms it pauses the task and resumes it next frame. This is ok, except that I have to scatter Multitasking.Yield() everywhere throughout my code, and it's a real mess.

Ideally, my code would automatically yield when it's been running too long. So, Is it possible to take a Lua function as an argument, and then execute it line by line (maybe interpreting Lua inside Lua, which I know is possible, but I doubt it's possible if all you have is a function pointer)? In this way I could automatically check the runtime and yield if necessary between every single line.

EDIT:: To be clear, I'm modding a game, that means I only have access to Lua. No C++ tricks allowed.

like image 448
Martin Avatar asked Apr 22 '10 00:04

Martin


2 Answers

check lua_sethook in the Debug Interface.

like image 84
Javier Avatar answered Oct 20 '22 19:10

Javier


I haven't actually tried this solution myself yet, so I don't know for sure how well it will work.

debug.sethook(coroutine.yield,"",10000);

I picked the number arbitrarily; it will have to be tweaked until it's roughly the time limit you need. Keep in mind that time spent in C functions etc will not increase the instruction count value, so a loop will reach this limit far faster than calls to long-running C functions. It may be viable to set a far lower value and instead provide a function that sees how much os.clock() or similar has increased.

like image 36
MaHuJa Avatar answered Oct 20 '22 19:10

MaHuJa