moonsharp-devs/moonsharp

Lua Script to delay

tommynanny opened this issue · 3 comments

Hi, I was wondering how I can add delay to my script, like "wait(2s)" or "sleep(2s)" before continue to execute the next line in my moonSharp Lua script.

You can use standard tools .net for example Thread.Sleep

	public class Utils1
        {
            public void Sleep(int ms) =>
                Thread.Sleep(ms);
        }
        public void SleepTest()
        {
            UserData.RegisterType<Utils1>();
	    var S = new Script();
            S.Globals["ds"] = new Utils1();
            DynValue res = S.DoString("ds:Sleep(4000)");
        }

I personally use this, hasn't caused me any grief. I expose it via the C# interp so it can be called as a Lua command. Very handy.

  public void Sleep(int milliseconds)
  {
      Task.Delay(milliseconds).Wait();
  }

you can try this

sleep = function(time)
    local t = 0
    repeat
        local T = os.time()
        coroutine.yield(0)
        t = t + (os.time()-T)
    until t >= time
end