0

私はこの質問への答えを数日間探していましたが、なんとかしてこの連結部分を省略し、いくつかの別々のループを使用して同じテーブルに異なる値を再挿入することができました...しかし私の質問は

デフォルトでは、table.sortは<を使用して配列要素を比較するため、数値の配列または文字列の配列のみを並べ替えることができます。table.sortが混合型の配列をソートできるようにする比較関数を記述します。ソートされた配列では、特定のタイプのすべての値をグループ化する必要があります。このような各グループ内では、数値と文字列は通常どおりに並べ替える必要があり、他のタイプは任意ですが一貫した方法で並べ替える必要があります。

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

私が言ったように、私は異なるforループを使用してこれを解決しましたが、テーブルのすべての要素を分析して、それを別のテーブルに割り当てる方法はありますか?「Tables、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
4

2 に答える 2

2

私が理解している限り、最初にタイプで並べ替え、次に値で並べ替えたいと考えています。独自のカスタム述語を作成して、並べ替えに渡すことができます

-- 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);
于 2012-10-09T13:55:43.210 に答える
0
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 のコメントに基づいて更新]

于 2012-10-09T17:14:32.400 に答える