我正在研究一個Python模塊,它充當舊的遊戲內腳本語言的解釋器。有很多的我發現我需要在路上變量,我模塊的頂部看起來是這樣的:變量範圍和整數代碼
from mufdatatypes import *
debugline=0
code=[]
debugline=0 #Line where something interesting starts
currentline=0 #Line where we currently are
infunc=0 #Need to know if we're in a function or not.
iflevel=0 #Need to track how far into ifs we are
inelse=0 #If we're in an if, have we already done an else?
looplevel=0 #Also need to know how many loops deep we're in
instrnum=0
charnum=0
gvarlist=[ "me": mufvariable(dbref(2)) , "loc" : mufvariable(dbref(0)) , "trigger" : mufvariable(dbref(-1)) , "command": mufvariable("") ]
item=''
structstack=[]
這是變得非常混亂。當時確實大部分定義的函數開始,它看起來像這樣:
def mufcompile(rawcode, primstable):
"""Compiles a source string into a list of instructions"""
global source
global code
global debugline
global currentline
global code #The actual instructions will be stored here.
global infunC#Need to know if we're in a function or not.
global iflevel #Need to track how far into ifs we are.
global inelse #If we're in an if, have we already done an else?
global looplevel #Also need to know how man loops deep we're in.
global addresstable #This will hold a table of function addresses.
global structstack #This list stack will be used to hold status info as we go further down complex statements
global instrnum #Number of instruction. Important for moving the EIP.
global vartable #Table of variables. Dictionary.
global charnum #Character in the line we're at.
global item
我有一種感覺,我的方式是不正確這樣做,或許,有趣的人究竟是誰知道他們在用Python做什麼。我知道變量可以在現場被聲明,但是如果任何高於我正在編寫的函數都有這些引用,它們將不會編譯,對吧?我也擔心全球化是如何發生的。導入此模塊的模塊是否可以訪問這些變量?我不希望他們。
我會建議使用一個類,以獲得擺脫'global'關鍵字,即使只創建該類的一個實例。 – 2012-03-06 21:51:47