Structuring code with lots of pauses and states?

Posted by Victorious on Wed 22 Jun 2016 10:44 AM — 5 posts, 23,149 views.

#0
Hi,

I'm trying to achieve something like the following.

-- a queue of items that i need to process in-game by using skills/spells 
while (queue is not empty) do
	local head = get first item
	getItemFromContainer() -- may fail
	processItem(head) -- this takes time, can fail, and uses mana. I also want to pause execution when I run out of mana to regenerate
	putItemInContainer() -- this step may fail as well
	removeCompletedItemFromQueue()
end


I've tried implementing it using wait.regexp to pause execution, but I'm finding that this is really messy. Is there a better way? Here's a simplified example. Aside from messiness, it is also difficult to shut it down because it relies on having a stack of functions (i'm not sure if that would even work) which are all paused at the appropriate times.


function mainLoop()
	wait.make(function()
		while true do
			local isQueueEmpty = #queue == 0
			
			if isQueueEmpty then
				print("Queue processing complete.")
				return
			end
			
			local head = queue[1]
			local getItemSuccess, getItemError = getItem(head.item, head.sourceContainer)
			
			if getItemSuccess, == false then
				print(getItemError)
				return
			end
			
			local processSuccess processError = processingLoop(head.item, head.sourceContainer, head.destContainer)
			if processSuccess, == false then
				print(processError)
				return
			end
			
		end -- while
	end) --wait
end --func

-- gets an item from the specified container
-- returns: a boolean indicating success, and an error message on failure
function getItem(item, container)
	-- send get command to mud
	-- use wait.regexp with 5 second timeout to determine success or error
end

-- processes an item
function processingLoop(item, sourceContainer, destContainer)
	while true do
		if regen required then 
			local regenSuccess, errorMsg = regenLoop(item, sourceContainer)
			-- return if regen not successful
		end
		
		-- send commands to mud, use wait.regexp again to determine whether processing is complete or not. Return true once item done
	end	
end

function regenLoop(item, sourceContainer)
	-- send command to put item back in container
	while regenRequired do
		wait.time(2)
	end
	
	-- send command to get item from container
end
Amended on Thu 23 Jun 2016 02:39 PM by Victorious
USA Global Moderator #1
Can you edit that post to use code tags and indenting?
Amended on Wed 22 Jun 2016 03:40 PM by Fiendish
Australia Forum Administrator #2
Template:codetag
To make your code more readable please use [code] tags as described here.
#3
Post edited - my apologies.

I did manual indentation this time; does putting it between the code tags do it automatically?
Australia Forum Administrator #4
No it doesn't (unlike some more modern sites).