Well, if you need a var in the OnUpdate or something happened frequently, I suggest you may try the coroutine. Also a test example :
1. First part is using a local var 'sum' to contains the sum result. And then we call it 10000 times.
2. Second part is using a coroutine to keep everything, we also can it 10000 times.
Lua Code:
do
oclock = os.clock
do
local sum = 0
function Sum(num)
for i = 1, num do
sum = sum + i
end
end
function callSum()
collectgarbage()
local startTime = oclock()
for i = 1, 10000 do
Sum(i)
end
local finsih = oclock()
print("Result is", sum)
print("Up-value cost ", finsih - startTime)
end
callSum()
end
print("----------------------------")
do
create = coroutine.create
resume = coroutine.resume
running = coroutine.running
status = coroutine.status
wrap = coroutine.wrap
yield = coroutine.yield
function Sum(num)
local sum = 0
while num do
for i = 1, num do
sum = sum + i
end
num = yield()
end
print("Result is", sum)
end
function callSum()
collectgarbage()
local startTime = oclock()
local thread = create(Sum)
for i = 1, 10000 do
resume(thread, i)
end
resume(thread)
local finsih = oclock()
print("Thread cost ", finsih - startTime)
end
callSum()
end
end
The result is :
Result is 166716670000
Up-value cost 1.406231
----------------------------
Result is 166716670000
Thread cost 0.853961
|
Normally, like an OnUpdate handler, you can do it like :
Lua Code:
local thread = create(function(...)
local var1, var2
while true do
-- Handle your code
yield()
end
end)
frame:SetScript("OnUpdate", function(self)
resume(thread)
end)
So, when your frame is visible, the thread will be called again and again, when not, the thread will be stop until the frame is shown again.
But, if your handle code is tiny, just use upvalue, in the previous example, if you change the code
Lua Code:
for i = 1, num do
sum = sum + i
end
To
The result should be
Result is 50005000
Up-value cost 0.0021880000000003
----------------------------
Result is 50005000
Thread cost 0.0052459999999996
|
So, the choose is based on your code, and the coroutine is more complex than the upvalue, if you do it wrong, it may crash your game.