Codea debug

Debugging Codea code has been a concern since the beginning. And this little trick has been around for a very long time also, but not much has been said about it. When a Codea project is running, at the bottom of the print panel are the words “type a command”. You can type a command there, press enter, and see the result of the command while the code is still running. It’s not very useful to constantly enter something, but then I thought, why not enter everything in a function. So here’s an example showing just that. Run this code and tap the “type a command” area. It will bring up the keyboard where you can enter a command. You can even pass parameter values to it. So enter dump(10) and press return. Everything in the dump function will execute. So if you want to debug your code by printing a bunch of values, just stick them in a function and type it’s name.

This is an example to dump a lot of variables, but you can also set variables to some value.

viewer.mode=STANDARD

function setup()
    a=25
    b=30
    c=35
    d=40
    s="qwertyuiop"
    x=0
    v=1
end

function draw()
    background(0)
    sprite(asset.builtin.Planet_Cute.Character_Horn_Girl,x,HEIGHT/2)
    x=x+v
    if x>WIDTH or x<1 then
        v=-v
    end
end

function dump(v)
    print("a",a)
    print("b",b)
    print("c",c)
    print("d",d)
    print("s",s)
    aa(v)   -- execute function aa passing a value
    print("x",x)
end

function aa(w)
    for z=1,w do
        print("sqrt z",z,math.sqrt(z))
    end
end

That’s a really neat trick @dave1707 thanks for sharing

Another way you can do similar is to use parameter.watch (for global variables or Lua expressions)

function setup()
    parameter.watch("a")
    parameter.watch("b")
    parameter.watch("c")
    parameter.watch("d")
    parameter.watch("s")
    parameter.watch("x")
    parameter.watch("v")

    a=25
    b=30
    c=35
    d=40
    s="qwertyuiop"
    x=0
    v=1
end

@Simeon I use parameter.watch sometimes, but I was thinking of a way to use the “type a command” more. Various functions can be created that dumps different variables. So depending on what you might want to see, you could run specific functions at different points of a program. So instead of having a long list of parameter.watch commands always running, “type a command” will let you be more specific at certain times.

Also, unlike parameter.watch that lets you only see a value, “type a command” will let you execute a function that might set a range of variables to specific value so you can see what a program does under specific conditions.

I was just trying to find a better use for “type a command” instead of just dumping a single variable.