2016-09-17 48 views
1

我有以下模塊:陣列型

module lexer 

export parseCode 

function parseCode(s::String) 
lexeme::Array{UInt32, 1} 
words = Dict("dup"=>UInt32(0x40000001), "drop"=>UInt32(0x40000002),  "swap"=> UInt32(0x40000003), "+"=> UInt32(0x40000004), "-"=> UInt32(0x40000005), "x"=> UInt(0x4000000c),"/"=>UInt32(0x40000006), "%"=> UInt32(0x40000007), "if"=> UInt32(0x40000008), 
    "j"=> UInt32(0x40000009), "print"=> UInt32(0x4000000a), "exit"=>UInt32(b)) 

    opcode = split(s) 
    for w in opcode 
    instruction::UInt32 
    instruction = get(words,w,0) 
    if instruction != 0 
     push!(lexeme,instruction) 
    end 
    end 
    push!(lexeme,UInt32(11)) 
    return lexeme 
end 
end 

功能parseCode解析中的字符串的話,併爲每個單詞取出對應的整數值,並將其推入一個數組詞法。 該函數然後返回數組test.jl:

require("stackProcessor") 
require("lexer") 

using stackProcessor 
using lexer 

#=prog=Array{UInt32,4} 
prog=[3,4,0x40000001, 5, 0x40000002, 3,0x40000003, 2, 0x40000004, 0x40000000] 

processor(prog) 
=# 
f = open("opcode.txt") 
s = readall(f) 
close(f) 
print(s) 

opcode = parseCode(s) 
print(repr(opcode)) 
processor(opcode) 

操作碼是應該得到的語義數組的副本的變量,但我得到以下錯誤:

oadError: UndefVarError: lexeme not defined 
in parseCode at C:\Users\Administrator\AppData\Local\atom\app-1.10.2\julia\lexer.jl:11 
in include_string at loading.jl:282 
in include_string at C:\Users\Administrator\.julia\v0.4\CodeTools\src\eval.jl:32 
in anonymous at C:\Users\Administrator\.julia\v0.4\Atom\src\eval.jl:84 
in withpath at C:\Users\Administrator\.julia\v0.4\Requires\src\require.jl:37 
in withpath at C:\Users\Administrator\.julia\v0.4\Atom\src\eval.jl:53 
[inlined code] from C:\Users\Administrator\.julia\v0.4\Atom\src\eval.jl:83 
in anonymous at task.jl:58 
while loading C:\Users\Administrator\AppData\Local\atom\app-1.10.2\julia\test.jl, in expression starting on line 17 

有趣的是它工作正常,現在它給了我這個錯誤。 我以爲在朱莉婭,數組返回作爲副本,所以我不能確定錯誤來自哪裏。

+0

也許'語義「最初是從全球環境中遺留下來的,因此之前就起作用了。要麼全局地重新定義它,要麼'parseCode'函數需要改變。 –

+0

@Dan:那麼我需要傳遞一個空數組作爲函數參數,然後用新內容填充數組? – JJTO

回答

3

lexeme::Array{UInt32, 1} 

聽起來像你希望初始化一個局部變量...但是,這是不是做了什麼。這只是一個現有變量的類型斷言。我假設那是產生錯誤的第11行,對吧?

錯誤是告訴你,在這一點你試圖斷言第11行lexeme變量的類型,該特定變量尚未定義到該函數中的那一點。

想必它的工作您清除您的工作區之前,因爲它是存在作爲一個全局變量或東西...

如果你想初始化,做這樣的事情,而不是:

lexeme = Array{UInt32,1}(0); 
+0

我忽略了(0)。我搞砸了......謝謝。 – JJTO

+1

更簡單的語法是'UInt32 []'。 –