lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

I've been looking for a way to run a Lua program that continuously executes functions at set intervals. Lua really needs a sleep(millisecs) function. I could write a c library to do this but I came up with the following method that uses coroutines:


t1 = {func1=0,func2=0}
t2 = {func1=0,func2=0}

function sleep(s,c)
 t1[c] = os.time()
 while(t2[c]-(t1[c]+s)<0)do
  coroutine.yield()
  t2[c] = os.time()
 end
end


co1 = coroutine.create(
 function()
  while(true) do
   print('func1')
   sleep(1,"func1")
  end
 end
)

co2 = coroutine.create(
 function()
  while(true) do
   print('func2')
   sleep(2,"func2")
  end
 end
)


coroutineTable = {co1,co2}
co = coroutineTable[1]
i=1
while(true) do
 coroutine.resume(co)
 --This alternates between all the coroutines in coroutineTable
 co = coroutineTable[math.mod(i,table.getn(coroutineTable))+1]
 i=i+1
end



I would be grateful for comments. Does anyone have any better ways?

Thanks,

Simon








-- 
___________________________________________________
Play 100s of games for FREE! http://games.mail.com/