【问题标题】:Values printing in pairs issue? Lua成对打印的值问题?卢阿
【发布时间】:2017-11-05 09:51:09
【问题描述】:

由于某种原因,似乎返回的国家都是成对返回的?如何更改代码使其仅返回“欧洲”中的国家/地区一次?

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")

【问题讨论】:

    标签: arrays class printing lua lua-table


    【解决方案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 时,都会创建 new list。它们都是唯一的 - 国家/地区对象添加到单个列表中。但再说一遍 - 我不知道你想要完成什么。

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      相关资源
      最近更新 更多