5

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.

Martin
  • 12,469
  • 13
  • 64
  • 128

2 Answers2

5

check lua_sethook in the Debug Interface.

Javier
  • 60,510
  • 8
  • 78
  • 126
  • This looks like it requires access to the C++ source? – Martin Apr 22 '10 at 01:47
  • 2
    The `debug` library is exported from Lua. You can call `debug.sethook()` directly from Lua. – Norman Ramsey Apr 22 '10 at 04:13
  • @Norman, excellent, this is looking pretty promising. @Javier, could you give a little more detail with how to use this, I'm not very familiar with C so the documentation is a little mystifying. – Martin Apr 22 '10 at 10:48
1

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.

MaHuJa
  • 3,148
  • 1
  • 18
  • 6
  • Probably the most graceful solution (indeed, I tried this originally), but it unfortunately does not work. See this discussion http://lua-list.2524044.n2.nabble.com/embedded-lua-in-web-based-REPL-td4766017.html –  May 02 '12 at 20:25