繁体   English   中英

在Lua中连接各种表

[英]Concatenating Various Tables In Lua

我一直在寻找这个问题的答案几天我设法以某种方式使用一个技巧来省略这个连接部分,只是使用几个单独的循环来重新插入不同的值到同一个表...但我的问题是

默认情况下,table.sort使用<来比较数组元素,因此它只能对数字数组或字符串数​​组进行排序。 编写一个比较函数,允许table.sort对混合类型的数组进行排序。 在排序数组中,给定类型的所有值应该组合在一起。 在每个这样的组中,数字和字符串应该照常排序,其他类型应该以任意但一致的方式排序。

A = { {} , {} , {} , "" , "a", "b" , "c" , 1 , 2 , 3 , -100 , 1.1 , function() end , function() end , false , false , true }

正如我所说,我使用不同的for循环解决了这个问题,但有没有办法只分析表中的每个元素然后将其分配给不同的表??? 喜欢:“表,Funcs,Nums,Strings,......”然后在分析完成后将它们连接在一起,以便在排序版本中拥有相同的表。

我对此的低效答案是:

function Sep(val)
local NewA = {}

   for i in pairs(val) do
      if type(val[i]) == "string" then
     table.insert(NewA,val[i])
      end
   end
for i in pairs(val) do
      if type(val[i]) == "number" then
     table.insert(NewA,val[i])
      end
   end

for i in pairs(val) do
      if type(val[i]) == "function" then
     table.insert(NewA,tostring(val[i]))
      end
   end

for i in pairs(val) do
      if type(val[i]) == "table" then
     table.insert(NewA,tostring(val[i]))
      end
   end

for i in pairs(val) do
      if type(val[i]) == "boolean" then
     table.insert(NewA,tostring(val[i]))
      end
   end

for i in pairs(NewA) do
   print(NewA[i])
end
end

据我所知,您希望先按类型然后按值对它们进行排序:您可以编写自己的自定义谓词并将其传递给排序

-- there would be need of custom < function since tables cannot be compared
-- you can overload operator < as well I suppose.
 function my_less (lhs, rhs)
    if (type (lhs) ~= "number" or type (lhs) ~= "string") then
        return tostring (lhs) < tostring (rhs) 
    else
        return lhs < rhs;
    end;
 end;

 -- the custom predicate I mentioned
 function sort_predicate (a,b)
    -- if the same type - compare variable, else compare types
    return (type (a) == type (b) and my_less (a, b)) or type (a) < type (b);
 end

 table.sort (A, sort_predicate);
A = { {}, {}, {}, "", "a", "b", "c", "2", "12", 1, 2, 3, -100, 1.1, 12, 11,
  function() end, function() end, false, false, true }

table.sort(A, function(a,b)
  if type(a) == type(b) and type(a) == 'number' then return a < b end
  return type(a)..tostring(a) < type(b)..tostring(b) end)

会给你这个:

{false, false, true, function() end, function() end,
 -100, 1, 1.1, 2, 3, 11, 12, "", "12", "2", "a", "b", "c", {}, {}, {}}

[根据@ tozka的评论更新]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM