Several people asked me during the last few days why Moai live coding is not supported by ZeroBrane Studio and I decided to take another look at why it has not been working as expected. After couple of hours of poking around I realized that the damage was self-inflicted: one of the options I added specifically for Moai (as requested by first beta users) was interfering with scratchpad logic. After resolving the conflict, live coding was back to live.
Just a bit of a background for those interested. Live coding works by continuously re-evaluating the code being edited in the running process. In order to do that, it needs to:
- abort or suspend the running process;
- re-evaluate the new code fragment in the context of the (suspended or aborted) process.
If your initial setup and the code you want to modify are in the same file, you may want to hide your setup code behind a check to avoid running it on subsequent evaluations (as I have done with
if not initialized check). Here is the code I've used:
if not initialized then MOAISim.openWindow ( "test", 320, 480 ) local viewport = MOAIViewport.new () viewport:setSize ( 320, 480 ) viewport:setScale ( 320, 480 ) local gfxQuad = MOAIGfxQuad2D.new () gfxQuad:setTexture ( "moai.png" ) gfxQuad:setRect ( -64, -64, 64, 64 ) prop = MOAIProp2D.new () prop:setDeck ( gfxQuad ) prop:setLoc ( 0, 80 ) local font = MOAIFont.new () font:loadFromTTF ( "arialbd.ttf", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?!", 12, 163) textbox = textbox or MOAITextBox.new () textbox:setFont ( font ) textbox:setRect ( -160, -80, 160, 80 ) textbox:setYFlip ( true ) textbox:setAlignment ( MOAITextBox.CENTER_JUSTIFY ) textbox:spool () local layer = MOAILayer2D.new () layer:setViewport ( viewport ) layer:insertProp ( prop ) layer:insertProp ( textbox ) MOAISim.pushRenderPass ( layer ) local thread = MOAIThread.new () thread:run(function () while true do update() coroutine.yield() end end) initialized = true end function update() textbox:setString("Moai live!") textbox:setLoc ( 0, -100 ) prop:setLoc(0, 60) end
You can copy this code as
main.lua in one of your Moai projects (and use
samples/hello-moai/ project) and go to
Project | Run as Scratchpad in ZeroBrane Studio. This will run your project in Moai; if you are new to this process, you may want to check my earlier post on configuring and debugging Moai projects.
When your script is running you can make changes in the
update() method: for example, you can update the string in the
setString call and should see the new value in the Moai window. You can also update numbers (manually or using sliders) and see the objects repositioned on the screen.
To use this functionality you need to get the most recent code from Github (or wait for ZeroBrane Studio v0.34).