Chinaunix首页 | 论坛 | 博客
  • 博客访问: 530523
  • 博文数量: 102
  • 博客积分: 2146
  • 博客等级: 大尉
  • 技术积分: 1146
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-09 17:32
文章分类

全部博文(102)

文章存档

2015年(14)

2014年(24)

2013年(5)

2012年(30)

2011年(16)

2010年(13)

分类: C/C++

2015-09-14 16:11:34


点击(此处)折叠或打开

  1. myTable = {7,1,13,6,89,4,56,2,54,6}

  2. -- 获得table中的最小值
  3. function GetMin(theTable)
  4.     myString = "myValue = math.min("
  5.     for index,value in ipairs(theTable) do
  6.         myString = string.format("%s%d%s", myString, value, ",")
  7.     end
  8.     -- 删除字符串后面多余的逗号
  9.     myString = string.sub (myString, 1, string.len(myString) - 1)
  10.     myString = string.format("%s%s", myString, ")")
  11.    -- 加载和运行一个字符串,这里是myValue = math.min...
  12.     loadstring(myString)() --run the chunk
  13.     print(myString) -- see the string
  14.     print(myValue) --see the result
  15.     return myValue
  16. end

  17. function GetMax(theTable)
  18.     myString = "myValue = math.max("
  19.     for index,value in ipairs(theTable) do
  20.         myString = string.format("%s%d%s", myString, value, ",")
  21.     end
  22.     --remove final comma
  23.     myString = string.sub (myString, 1, string.len(myString) - 1)
  24.     myString = string.format("%s%s", myString, ")")
  25.     loadstring(myString)() --run the chunk
  26.     print(myString) -- see the string
  27.     print(myValue) --see the result
  28.     return myValue
  29. end

  30. function Sort(theTable, direction)
  31.     if direction ~= 1 then
  32.         table.sort(theTable)
  33.     else
  34.         function Reverse(a, b)
  35.             if a < b then
  36.                 return false
  37.             else
  38.                 return true
  39.             end
  40.         end
  41.         table.sort(theTable, Reverse)
  42.     end
  43. end

  44. 使用:
  45. -- 从小到大排序
  46. Sort(myTable, 1)
  47. for i=1, table.getn(myTable) do
  48.   print(myTable[i])
  49. end
  50. 或者
  51. table.sort(myTable)
  52. for i=1, table.getn(myTable) do
  53.   print(myTable[i])
  54. end

  55. -- 从大到小排序
  56. Sort(myTable, 1)
  57. for i=1, table.getn(myTable) do
  58.   print(myTable[i])
  59. end
阅读(546) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~