2017-06-04 171 views
1

由於某種原因,似乎要退貨的國家都是成對返回的?您如何更改代碼,以便只返回「歐洲」國家的國家一次?成對打印問題? Lua

function newcountry(continent,country) 
    local object = {} 
    object.continent = continent 
    object.country = country 

    local list = {} 

    for i in pairs(object) do 
    if object.continent == "Europe" then 
    table.insert(list, object.country) 
    print(object.country) 

    end 
end 

    return object 
end 


a = newcountry("Africa","Algeria") 
b = newcountry("Europe","England") 
c = newcountry("Europe","France") 
d = newcountry("Europe","Spain") 
e = newcountry("Asia","China") 

回答

1

我不知道你想什麼,此代碼來完成,而是要回答你的問題:

function newcountry(continent,country) 
    local object = {} 
    object.continent = continent 
    object.country = country 
    local list = {} 
    if object.continent == "Europe" then 
     table.insert(list, object.country) 
     print(object.country) 
    end 
    return object 
end 

該代碼將在歐洲各國印刷只有一次。當出現循環時,它會打印兩次國家名稱,因爲它爲object表(continentcountry,因此兩次)的每個元素都執行了該操作。

Generic for loops in 用Lua編程(第一版)。

我還想指出list目前是無用的。它不會被退回並保持在當地。最重要的是,每次撥打電話newcountry時都有新的list創建。他們都是獨特的 - 國家對象是不是添加到單個列表。但是,我再也不知道你在努力完成什麼。