值打印成对问题? Lua

由于某些原因,似乎返回的国家都是成对返回的? 如何更改代码,使其只返回'欧洲'国家一次?

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

  local list = {}

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

  end
end

  return object
end

a = newcountry("非洲","阿尔及利亚")
b = newcountry("欧洲","英国")
c = newcountry("欧洲","法国")
d = newcountry("欧洲","西班牙")
e = newcountry("亚洲","中国")
点赞
用户4567755
用户4567755

我不确定你试图用这段代码做什么,但是为了回答你的问题:

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,因此打印两次)执行此操作。

Programming in Lua 中的 通用 for 循环(第一版)。

我还想指出,目前的 list 是相当无用的。它没有被返回并保持在本地。此外,每次你调用 newcountry 时都会创建一个 新的 list。它们都是唯一的 - 国家对象并没有添加到单个列表中。但是 - 再次说明 - 我不知道你试图做什么。

2017-06-04 14:36:43