Skip to content

Cobalt UI

ebernerd edited this page Jul 1, 2016 · 10 revisions

Cobalt-UI

Cobalt-UI (internally referred to as "cui") is a UI lib written for Cobalt that allows you to easily make UI-based programs using Cobalt's callback system.

Installation

To install Cobalt-UI, you must first get the cobalt-ui folder and place it in your ComputerCraft project. Then, write these lines of code:

local cobalt = dofile( "cobalt" ) --require cobalt's main lib
cobalt.ui = dofile( "cobalt-ui/init.lua" ) --initialize cobalt-ui

Note: you do not have to refer to it as cobalt.ui. For the sake of continuity, all Cobalt-UI functions written in the wiki have the library loaded as cobalt.ui

Making Objects

To start your Cobalt-UI project, you must create a rooted object.

cobalt.ui.new( data ) - returns a new rooted Panel. It has no parent object, so self.parent calls will not work. For all UI programs you need at least one rooted object

Once you have a rooted object, you can then use <obj>:add( type, data ) to add children to the object <obj>.

Adding the Callbacks

Since Cobalt is callback based, we're going to need to insert Cobalt-UI's callbacks into your main project.

local cobalt = dofile( 'cobalt' )
cobalt.ui = dofile( 'cobalt-ui/init.lua' )

--your code

function cobalt.update( dt )
   --your code
   cobalt.ui.update( dt )
end

function cobalt.draw()
   --your code
   cobalt.ui.draw( )
end

function cobalt.mousepressed( x, y, button )
   --your code
   cobalt.ui.mousepressed( x, y, button )
end

function cobalt.mousereleased( x, y, button )
   --your code
   cobalt.ui.mousereleased( x, y, button )
end

function cobalt.keypressed( keycode, key )
   --your code
   cobalt.ui.keypressed( keycode, key )
end

function cobalt.keyreleased( keycode, key )
   --your code
   cobalt.ui.keyreleased( keycode, key )
end

function cobalt.textinput( t )
   --your code
   cobalt.ui.textinput( t )
end

Example

This example will output a simple button that changes colour when you press it.

local cobalt = dofile( "cobalt" )
cobalt.ui = dofile( "cobalt-ui/init.lua" )

local Panel = cobalt.ui.new({ w = "50%", marginleft="25%", h = "50%", margintop = "25%" })
local Button = Panel:add("button", { wrap="center", y = 4})
Button.onclick = function()
	Button.backColour = 2 ^ math.random( 1, 15 )
end

function cobalt.draw()
  cobalt.ui.draw()
end

function cobalt.mousepressed( x, y, button )
	cobalt.ui.mousepressed( x, y, button )
end

function cobalt.mousereleased( x, y, button )
	cobalt.ui.mousereleased( x, y, button )
end

cobalt.initLoop()

Result: result