Log In  

Hi all !

Is it possible to do something like that ?

try
  object:foo(param)
else
  print("object has no foo method")
end

Thanks ;)
M.Luge

P#42767 2017-07-25 06:49 ( Edited 2017-07-25 22:27)

You can use assert to test for a condition and stop the program if it return false. So if you wanted to check if an object had a foo method, you could do this:

assert(object.foo)

and the program would stop and say "assertion failed" if the object didn't have a foo method.

As far as I know, there's no way to display a custom message with assert in PICO-8 (unlike vanilla Lua), and you can't choose to run some other code when you encounter an error, so it's certainly not as fancy as try/catch statements in some other languages.

P#42768 2017-07-25 07:19 ( Edited 2017-07-25 11:19)

Ok, thanks. I'll try with the assert method.

o/

P#42769 2017-07-25 07:43 ( Edited 2017-07-25 11:43)

from my best guess at what your pseudocode is meant to do, this would be basically analogous to it:

if type(object.foo) == "function" then
    object:foo(param)
else
    print("object has no foo method")
end

although it doesn't also check that object is bound to a table. if you want that, also check type(object) == "table". it also doesn't cover any errors the method call itself might result in, which would have to be handled case-per-case based on what they are.

standard lua has more robust exception handling in the form of pcall and related interfaces, but it's not included in pico-8 as far as i can tell.

P#42796 2017-07-25 17:39 ( Edited 2017-07-25 21:39)

Yep, i read something about the pcall function. I'm sad this function is not part of the pico8 software.

What i want to do is that the caller doesn't care if the other object is able to respond to the call method. It's a Python & Ruby good practice and i'm aware with that.

Well, thanks for your answers ;)

P#42800 2017-07-25 18:27 ( Edited 2017-07-25 22:27)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 23:21:30 | 0.006s | Q:12