The First Page of Chapter One

Well, after four weeks, that’s where I remain in “Programming in Lua, 2nd Ed.” Here is the woefully simple example that I am unable to run in Codea:

-- defines a factorial function
function fact(n)
     if n==0 then
          return 1
     else return n * fact(n-1)
     end
end

print ("enter a number: ")
a = io.read("*number")     -- read a number
print (fact(a))

I’m aware that there’s no io.read in Codea, but every single workaround I’ve attempted has been a failure. Is anyone out there able to help me solve this? So I can move on to the freaking second page??

You can’t just run normal Lua programs in Codea. Although Codea uses the Lua language, it does not run the code in the same way as the standard Lua interpreter. Codea controls the main loop and invokes your code by calling functions when certain events happen. It calls setup() to initialise your program, draw() every frame to animate and draw the display, touched(t) when the user performs a touch gesture, collide(c) when physics bodies collide, etc.

It’s much easier to learn by starting with something that works and changing it bit by bit. So I suggest: start by reading some code in the example projects. Make an editable copy of a simple one. Fiddle around with it to experiment.

-- defines a factorial function
function fact(n)
     if n==0 then
          return 1
     else return n * fact(n-1)
     end
end

function setup()
    showKeyboard()
    t = "" --where the text will be typed into
    a = nil --where the number will be put
end

function draw()
    background() --reset background so that text doesn't blur
    --each line of text 50 pixels beneath the prior one from the top
    text("enter a number",WIDTH/2,HEIGHT -50)
    text(t,WIDTH/2,HEIGHT -100)
    if tonumber(t) ~= nil then --if it's numeric then...
        a = tonumber(t) 
        text(fact(a),WIDTH/2,HEIGHT -150)
    end
end

function keyboard(key)
    --putting keyboard presses in global t
    if key ~= nil then
        if string.byte(key) == nil then
            --backspace
            if string.len(t) > 0 then
                t = string.sub(t,1,string.len(t) - 1)
            end
        else
            if t == nil then t = key
            else t = t .. key end
        end
    end
end

@Nat and @Ipda41001:

I really appreciate these responses. @Nat, thanks for the ground rules, and @Ipda41001, thanks for the code! This shows me where I was on the right track (and where I was definitely not). Much gratitude to you both.