Page 1 of 1

How to use functions defined inside screen?

Posted: Sat Apr 27, 2024 6:50 am
by Milkymalk
How can I use functions that are inside screens? I tried understanding dragging when I wrote this, and the card_dragged function that is the drag callback works flawlessly, but when it wants to call the function snapcard, I get an error that it is not defined.

I know I can just put the functions outside, but I like my data tidy and grouped.

Code: Select all

screen dragtest():
    python:
        def snapcard(card, slot):
            card.snap(slot.x,slot.y)
            return

        def card_dragged(drags, drop):
            if not drop:
                return
            card = drags[0].drag_name
            slot = drop.drag_name
            snapcard(drags[0], drop)
            return

# insert regular screen stuff

Re: How to use functions defined inside screen?

Posted: Sat Apr 27, 2024 12:26 pm
by Ocelot
It is simple: you cannot.

Function definition should happen in init phase and Screen Language does not have any way to execute code in init phase.

Re: How to use functions defined inside screen?

Posted: Sat Apr 27, 2024 5:33 pm
by Milkymalk
Not that I don't believe you, but why is it then that the callback function works?

Re: How to use functions defined inside screen?

Posted: Sat Apr 27, 2024 6:50 pm
by Ocelot
That's the beauty of the undefined behavior: anything can happen. Even that incorrect code will work.

While RenPy wants python functions to be defined during init phase, it does not take any additional steps to ensure that code that violates that principle won't work. Your callback simply didn't trip anything which requires that, while attempting to use other did (though I highly suspect that you actually run into scope issues there, which is another problem that arises from attempting to define something that is intended to be defined globally in local scope).

This is like running a red light or driving drunk: for many people it works and they did not run into any probles eve. Doesn't mean that it is a good idea to do so.

Re: How to use functions defined inside screen?

Posted: Sat Apr 27, 2024 7:20 pm
by Milkymalk
That's funny. I always imagined screens to behave like classes in that regard, so that I *can* define local functions that exist in the namespace of that screen only; and I'm sure I already used this to have small specialized functions there, probably small and straightforward enough (like a pythagorean calculation of distance) that it all worked.
So that's out the window :( Meh.