2015-12-19 24 views
2

我目前正在學習這種偉大的茱莉亞語言,但我面臨的困難是我最好的朋友Google似乎沒有回答(也許我的搜索技能很差)。無法在另一個模塊中定義的函數中創建在模塊M1中定義的類型的新實例M2

反正...我的背景是這樣的:

我有兩個模塊:

  1. M1.jl

    module M1 
    type T 
        t1::Int64 
    end 
    
    T() = T(0) 
    
    export T 
    end 
    
  2. M2.jl

    module M2 
    function create() 
        isdefined(:T) ? T() : "undef" 
    end 
    
    export create 
    end 
    

我只想調用create函數來實例化類型爲T的對象,如果類型已定義。在這裏我所試圖做的(模塊M1M2假定路徑):

using M1; 
using M2; 

create() 

然後我得到這個ERROR: UndefVarError: T not defined而我會有望得到M1.T(0)因爲T在解釋或者在被稱爲至少"undef"如果模塊M1沒有加載到我的會話中。

另外,如果我這樣做: 使用M1;使用M2的 ;

isdefined(:T) ? T() : "undef" 

然後一切都很好,我得到:M1.T(0)

所以我的問題是:

  1. 是可以使功能create「看」模塊中定義的類型加載當前會議?
  2. 能否請您解釋一下whay我得到這個錯誤ERROR: UndefVarError: T not defined因爲如果T在我的背景沒有定義,isdefined必須返回false這樣"undef"應該已經回來了?

非常感謝提前。

問候。

+0

爲什麼你不能在實際類型爲'create'通過一個完整的路徑?無論如何,'M2'顯然依賴於'M1',所以依賴必須以某種方式進行調解。 –

+0

對不起函數'create'的參數,它是複製粘貼錯誤...謝謝你。沒錯,'M2'取決於'M1',但我認爲這將是一種通過模塊'Main'滿足這種依賴關係的方法...... –

回答

0

朱莉婭文件描述的isdefined()的功能如下:

隨着單個符號參數,測試在current_module()具有該名稱的全局變量是否被定義。

但是哪個模塊是current_module()

要找到我添加了一個whatiscurrentmodule()功能M2上述問題的答案,並將其加載到Main什麼我有是這樣的:

julia> module M2 

     function whatiscurrentmodule() 
      println("current_module=",current_module()) 
     end 

     function create(type_name::AbstractString) 
       isdefined(:T) ? T() : "undef" 
     end 
     export create 
     println("current_module=",current_module()) 
     end; 
current_module=M2 

julia> M2.whatiscurrentmodule() 
current_module=Main # current_module is the caller module 

現在是清楚什麼在發生運行 - 時間:isdefined()回報true因爲:T在主叫範圍定義,但T()不能罰款:T,因爲它不會導入M2,爲了解決這個問題,一個可能迫使M2使用M1

julia> module M2 
     using M1 
     function create(type_name::AbstractString) 
      isdefined(:T) ? T() : "undef" 
     end 
     export create 
     end; 

julia> using M1 

julia> M2.create("") 
M1.T(0) 

編輯:或不進口任何東西,但添加到:T

julia> module M2 
     function create(type_name::AbstractString) 
      isdefined(:T) ? current_module().T() : "undef" 
     end 
     export create 
     end; 

julia> using M1 

julia> M2.create("") 
M1.T(0) 
+0

感謝Reza爲您解釋'isdefined'函數發生了什麼。現在更清楚了。你的'M2'模塊強制進入'M1'的建議是可以的,但實際上我的用例比以往復雜一些。事實上,'create'函數實際上能夠創建在不同模塊中定義的大量類型(即不僅是'T')的實例。但是,如果沒有「簡單」的解決方案來強制'create'來查看'Main'中定義的內容,我會處理這個問題。 –

+0

@羅蘭多納特,我希望另一種方法的作品 –

+0

完美的禮薩!這正是我正在尋找的解決方案。謝謝! –

相關問題