Variable Scope Issue

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
Message
Author
DoubleProlix
Regular
Posts: 33
Joined: Thu Oct 19, 2017 8:04 pm
Contact:

Variable Scope Issue

#1 Post by DoubleProlix »

I've got a function that determines the ratio between two values:

Code: Select all

 
        def ratio(x, y):
            rat = round(x/(x+y),1)
 
Most of the time this works fine. However, when using it with variables belonging to an npc object to get the ratio of "good" interactions with the player vs "bad", it always returns 0.

I think it's a matter of scope, but I'm not sure, or how to let the ratio function access the npc object's variables (call them npc.goodInteraction and npc.badInteraction).

Is there a way to make this work, or will I need to create global NPCGoodInteraction and NPCBadInteraction variables for each character?
Current Project: Thaumarotica - an occult erotic thriller
SubscribeStar - Patreon - Itch.io

User avatar
Remix
Eileen-Class Veteran
Posts: 1628
Joined: Tue May 30, 2017 6:10 am
Completed: None... yet (as I'm still looking for an artist)
Projects: An un-named anime based trainer game
Contact:

Re: Variable Scope Issue

#2 Post by Remix »

If you are passing the variables into the function or method, the variables will become aliases to the passed variable, meaning that should you alter the value you would only alter the alias and not the original.

Without seeing your npc objects or knowing why rat is calculated rather than returned I'd only be guessing at a best approach... Have you considered adding a @property method (or just a get_ratio(self) method) to the npc class and just letting it return a ratio?
Frameworks & Scriptlets:

rames44
Veteran
Posts: 233
Joined: Sun May 29, 2016 4:38 pm
Contact:

Re: Variable Scope Issue

#3 Post by rames44 »

Stupid question - are the npc variables integers or floating point numbers? Python 2 still implements integer division as a “floor” operation, so that 5/2=2, not 2.5. This was one of the significant changes in Python 3. Thus, if x and y are both integers, x/(x+y) will always return 0 unless y is zero, at which point it will return 1.

https://stackoverflow.com/questions/183 ... r-division

Post Reply

Who is online

Users browsing this forum: Google [Bot], Mica