Variable Overwriten?
Author |
Message |
Zren
|
Posted: Fri Aug 06, 2010 4:53 am Post subject: Variable Overwriten? |
|
|
Hokay. So I've got some globalish variables. There a couple of small classes that reference the globals for rendering/default ranges. The thing is, if I try to add code to modify these variables inside main() [the sections in between ######], python goes crazy and tells me it was referenced at the beginning. So my question is, why did adding this section overwrite or make python forget the earlier declaration and is there a way to make it reference the globals then overwriting with local variables? Or is it my logic and should I have it so each class loads the variable into itself, then modify that reference? Well it's probably the logic, but is there an alternate way?
The actual error: UnboundLocalError: Local variable CHUNK_W[/Any "global variable"] referenced before assingnment
Python: |
CHUNK_X = 16
CHUNK_Y = 16
BLOCK = 8
CHUNK_W = CHUNK_X*BLOCK
CHUNK_H = CHUNK_Y*BLOCK
VIEW_W = 5
VIEW_H = 4
VIEW = (VIEW_W*CHUNK_W, VIEW_H*CHUNK_H)
def main():
while running:
key=pygame.key.get_pressed()
if True in key:
####################################################
if key[pygame.K_q] or key[pygame.K_w]:
if key[pygame.K_q]:
BLOCK +=1
VIEW_W += 1
VIEW_H += 1
if key[pygame.K_w]:
BLOCK -=1
VIEW_W -= 1
VIEW_H -= 1
CHUNK_W = CHUNK_X*BLOCK
CHUNK_H = CHUNK_Y*BLOCK
VIEW = (VIEW_W*CHUNK_W, VIEW_H*CHUNK_H)
####################################################
# Where it's supposidly being referenced before assingnment
hoverChunk = (mouse[0][0]/CHUNK_W+camera[0], mouse[0][1]/CHUNK_H+camera[1])
if __name__ == '__main__':
main()
|
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
TheGuardian001
|
Posted: Fri Aug 06, 2010 6:27 am Post subject: Re: Variable Overwriten? |
|
|
I could be wrong here (been a while since I've used Python), but don't you need to specify "global" if you want to modify a global variable from inside a method?
IE, instead of
code: |
CHUNK_W = CHUNK_X*BLOCK
|
You would use
code: |
global CHUNK_W = CHUNK_X*BLOCK
|
If you don't specify global, I believe Python will create a new local variable by that name, and since you go out of scope immediately afterward, that value is lost.
I'm not sure why that would cause that specific error though, since you should still have the initial values available... |
|
|
|
|
|
|
|