2017-06-04 192 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创建。他们都是独特的 - 国家对象是不是添加到单个列表。但是,我再也不知道你在努力完成什么。