View Single Post
09-01-10, 01:31 PM   #8
TLH
A Murloc Raider
AddOn Author - Click to view addons
Join Date: Aug 2010
Posts: 8
Originally Posted by Vrul View Post
Can you give an example where this occurs (not just saying its "like" something)?

Yus, that I can! Example is below.

I also think I've found and corrected the 'problem', though I still don't quite understand what goes wrong. It seems to be in the syntax of declaring the function. In Wowwiki's page on Object-oriented programming, they use syntax such as:

Code:
function Character:new()
	-- code
end
This 'appears' to work fine until coroutines are involved, where the declaration 'seems' to need to be:

Code:
Character.new = function()
	-- code
end

I've made a quick mockup scenario to illustrate it here. All this program actually does is multiply two numbers together using the worst method possible, but it makes a good example
To try it with the fail-syntax, comment out line 8 and remove the comment from line 5.

Code:
-- Make a namespace
test={};

-- This syntax fails
--function test:Multiply(a, b)

-- This syntax succeeds
test.Multiply = function(a, b)
	local ans=0;
	
	while b>0 do
		ans = ans+a;
		b = b-1;

		-- Drop out here so as to run the While only once per Resume
		coroutine.yield();
	end
	
	return ans;
end


-- Create the thread
test.co = coroutine.create(test.Multiply);

-- This function would be called over time, e.g. with OnUpdate
test.Run = function()
	local flag, out;
	
	-- Multiply 3 by 5.
	flag, out = coroutine.resume(test.co, 3, 5);
	
	if out==nil then
		-- Not yet complete
		print("Iteration");
	else
		-- Complete
		print(out);
	end
end


-- Simulate multiple calls to Run
for i=1,6 do
	test.Run();
end
*

Declaring the function with 'function test:Multiply(a, b)' gives output:
Code:
11: attempt to compare number with nil
cannot resume dead coroutine
cannot resume dead coroutine
cannot resume dead coroutine
cannot resume dead coroutine
cannot resume dead coroutine
Declaring the function with 'test.Multiply = function(a, b)' gives output:
Code:
Iteration
Iteration
Iteration
Iteration
Iteration
15
*

Line 11 is the one containing 'b>0', so I guess test.Multiply isn't receiving its arguments for some reason. The only difference there is the line containing 'function', and there lies the mysterious part ^^

Last edited by TLH : 09-01-10 at 01:35 PM.
  Reply With Quote