tablelib.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package lua
  2. import (
  3. "sort"
  4. )
  5. func OpenTable(L *LState) int {
  6. tabmod := L.RegisterModule(TabLibName, tableFuncs)
  7. L.Push(tabmod)
  8. return 1
  9. }
  10. var tableFuncs = map[string]LGFunction{
  11. "getn": tableGetN,
  12. "concat": tableConcat,
  13. "insert": tableInsert,
  14. "maxn": tableMaxN,
  15. "remove": tableRemove,
  16. "sort": tableSort,
  17. }
  18. func tableSort(L *LState) int {
  19. tbl := L.CheckTable(1)
  20. sorter := lValueArraySorter{L, nil, tbl.array}
  21. if L.GetTop() != 1 {
  22. sorter.Fn = L.CheckFunction(2)
  23. }
  24. sort.Sort(sorter)
  25. return 0
  26. }
  27. func tableGetN(L *LState) int {
  28. L.Push(LNumber(L.CheckTable(1).Len()))
  29. return 1
  30. }
  31. func tableMaxN(L *LState) int {
  32. L.Push(LNumber(L.CheckTable(1).MaxN()))
  33. return 1
  34. }
  35. func tableRemove(L *LState) int {
  36. tbl := L.CheckTable(1)
  37. if L.GetTop() == 1 {
  38. L.Push(tbl.Remove(-1))
  39. } else {
  40. L.Push(tbl.Remove(L.CheckInt(2)))
  41. }
  42. return 1
  43. }
  44. func tableConcat(L *LState) int {
  45. tbl := L.CheckTable(1)
  46. sep := LString(L.OptString(2, ""))
  47. i := L.OptInt(3, 1)
  48. j := L.OptInt(4, tbl.Len())
  49. if L.GetTop() == 3 {
  50. if i > tbl.Len() || i < 1 {
  51. L.Push(LString(""))
  52. return 1
  53. }
  54. }
  55. i = intMax(intMin(i, tbl.Len()), 1)
  56. j = intMin(intMin(j, tbl.Len()), tbl.Len())
  57. if i > j {
  58. L.Push(LString(""))
  59. return 1
  60. }
  61. //TODO should flushing?
  62. retbottom := L.GetTop()
  63. for ; i <= j; i++ {
  64. L.Push(tbl.RawGetInt(i))
  65. if i != j {
  66. L.Push(sep)
  67. }
  68. }
  69. L.Push(stringConcat(L, L.GetTop()-retbottom, L.reg.Top()-1))
  70. return 1
  71. }
  72. func tableInsert(L *LState) int {
  73. tbl := L.CheckTable(1)
  74. nargs := L.GetTop()
  75. if nargs == 1 {
  76. L.RaiseError("wrong number of arguments")
  77. }
  78. if L.GetTop() == 2 {
  79. tbl.Append(L.Get(2))
  80. return 0
  81. }
  82. tbl.Insert(int(L.CheckInt(2)), L.CheckAny(3))
  83. return 0
  84. }
  85. //