Continue on error

Consider this code in a draw loop

    f=loadstring("x==34*math.sin(30)")
    f()
    print(x)

An error will occour because of the double == that should be =

What if I want to continue execution leaving out the faulty line.
How do I catch the error and discharge the line without manually checking if everything is in order ?

Re Peter

Think Mr Peter Think B-)
Very simple solution

f=loadstring("x==34*math.sin(30)")
    if f == nil then else f() print(x) end

Re Peter

@macflyerdk you might want to take a look at the pcall function, too. This allows you to call Lua code that may have runtime errors, and if so, handle them during execution of your program.

The documentation is here:

http://www.lua.org/pil/8.4.html

Relevant example:


if pcall(foo) then
      -- no errors while running `foo'
      ...
else
      -- `foo' raised an error: take appropriate actions
      ...
end

Thanks :slight_smile:

Thanks @Simeon. I will have look at the pcall function.
I am allways amazed how you find the time to develop Codea and at the same time answer these tiny problems the end users have :slight_smile: Especially because I was able to find an answer myself on this one :wink:
Re Peter

Sorry, but I have to point out two shortcuts. One: Instead of writing

if f == nil then else f() print(x) end

You could use:

if f ~= nil then f() print(x) end

Or:

if not f == nil then f() print(x) end

Sorry, but from experience I myself find using

if ... then else ... end

looks a bit sloppy.

Because I did not fill out what should happen on error yet :wink:
But you are of course right…

Sorry, one more thing. I think you can check if a variable exists by calling something like

a = o
if a then
    ... -- a is a variable
else
    ... -- a is not a variable
end

This also goes for functions, but without parentheses.

f=loadstring("x==34*math.sin(30)")
if f then
    f()
    print(x)
else
    print("No function named f!")
end

@SkyTheCoder that will check if a variable exists but it will also implicitly check whether it is true or false if it is a Boolean for example, so it’s safest to always check whether it is equal to nil or not if you want to know for sure :slight_smile:

if a ~= nil then

end

My favourite in Lua is

a = a or 10

Which is so useful for setting defaults for optional parameters

@Ignatz it is very, though when I first saw it i thought it was a bitwise calculation :confused:

a shame there is no bitwise calc in Lua

That it is, it could be handy, especially for image processing off the camera type tasks :slight_smile: though a quick google turned this up http://lua-users.org/wiki/BitwiseOperators which has some pure lua implementations but there’s certainly no performance benefit to them :frowning:

@Ignatz Dang it, I was using that but I had it in the wrong order…

a = 10 or a