Basic Moai Program Example

I’ll walk through a really basic Moai program to show how to get setup. The first thing you need to do is setup a new window and a viewport:

local width = 400
local height = 400

MOAISim.openWindow ( "Hello World", width, height )


To declare a variable in Lua, you can just name it and set it to a value.  Variables are global by default, and you can put the keyword “local” in front of it to make it local.  Here we’re going to start by defining a 400 by 400 pixel window with the title “Hello World”.  MOAISim is a global object you can use to create the window.  We also set the background color of the window by calling setClearColor on MOAIGfxDevice to white (I think this is RGBA format).

local viewport = ()
viewport:setSize ( width, height )
viewport:setScale ( width, height )

local layer = ()
layer:setViewport ( viewport )

local layers = {}
layers[1] = layer

The next thing you have to do is tell Moai what you actually want to draw.  You can this by passing it an array of layers, which get drawn on top of each other.  You can have as many layers as you want, but we’ll start with just one here.  Additional layers might be useful for drawing debugging information, the UI or keeping the background separate from the foreground.

Each layer needs a viewport, which defines what is actually shown.  We want a viewport that is 400 by 400, with each pixel being one unit. will create the viewport for you.

Then we create the actual layer by calling, and setting the viewport into that layer.

Finally we create an array, pass in our new layer (arrays are indexed starting at 1 in Lua), and tell the MOAIRenderMgr about it.

local gfxQuad = ()
gfxQuad:setTexture ( "sprites/bear.png" )
gfxQuad:setRect ( -64, -64, 64, 64 )

local prop = ()
prop:setDeck ( gfxQuad )
layer:insertProp ( prop )

At this point you should see a white screen when you start up.  The last thing we want to do in our test is actually draw a picture on the Window.

Moai uses things called Decks and Props to define resources and draw them to the screen.  A Deck is the definition some geometry (the shape, textures), and a Prop is a reference to a Deck that we can actually draw (including location, scale, rotation).  A single Deck might have a bunch of Props referencing it.

Here we define the Deck to be a square (MOAIGfxQuad2D) that is 128×128, centered around the origin (with setRect), and a texture at location “sprites/bear.png” (with setTexture).  Then we create a new Prop of type MOAIProp2D based off of that Deck.  We then add this to the layer, and it should show up at the default spot, at 0,0.

At this point you have everything you need to read a really basic Moai program.  In order to do anything more complicated, you’ll need some basic knowledge of Lua.  I’ll cover the parts of the language that I found interesting, and how to implement some basic OOP design in the next few posts.

Leave a Reply