Skip to content

cobalt.initLoop()

ebernerd edited this page Aug 14, 2016 · 5 revisions

cobalt.initLoop()

The function cobalt.initLoop() (also known as cobalt.init()) starts the callback-wrapper for ComputerCraft. Normal ComputerCraft programming is event based, meaning you use a function to pull an event, and deal with it's information afterwards. Cobalt is callback based, so you write a function that encompasses what you want to do when a specific event happens, while letting other events happen simultaneously.

cobalt.initLoop() should always be called on the last line of a Cobalt project. If it is done anywhere else, the program will crash, not work, or yield unexpected results.

The internal code wraps ComputerCraft's event based system into a callback based one. It does so like this:

--As of version 1.1_0
function cobalt.initLoop()
	while cobalt._mainloop do

		local e, a, b, c, d, e
		if cobalt.raw then
			e, a, b, c, d, e = os.pullEventRaw()
		else
			e, a, b, c, d, e = os.pullEvent()
		end
		if e == "char" then
			if cobalt.textinput then	cobalt.textinput( a ) end
		elseif e == "key" then
			cobalt._keypressed( a, keys.getName( a ) )
		elseif e == "key_up" then
			cobalt._keyreleased( a, keys.getName( a ) )
		elseif e == "mouse_click" then
			if cobalt.mousepressed then cobalt.mousepressed( b, c, a ) end --b, c, a to keep love.mousepressed syntax as( x, y, button ), not ( button, x, y )
		elseif e == "mouse_up" then
			if cobalt.mousereleased then cobalt.mousereleased( b, c, a ) end
		elseif e == "rednet_message" then
			if cobalt.rednetreceive then cobalt.rednetreceive( a, b, c ) end
		elseif e == "mouse_drag" then
			if cobalt.mousedrag then cobalt.mousedrag( x, y ) end
		elseif e == "timer" then
			if a == cobalt.updatetimer then
				if cobalt.update then cobalt.update( cobalt.updatespeed ) end
				cobalt.updatetimer = os.startTimer( cobalt.updatespeed )
				cobalt._draw()
			end
		end


	end
end

#cobalt.initOnce() cobalt.initOnce() is a function you can run to see if you only want the loop to update once, draw once, and exit.