tablelib.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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(emptyLString)
  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(emptyLString)
  59. return 1
  60. }
  61. //TODO should flushing?
  62. retbottom := L.GetTop()
  63. for ; i <= j; i++ {
  64. v := tbl.RawGetInt(i)
  65. if !LVCanConvToString(v) {
  66. L.RaiseError("invalid value (%s) at index %d in table for concat", v.Type().String(), i)
  67. }
  68. L.Push(v)
  69. if i != j {
  70. L.Push(sep)
  71. }
  72. }
  73. L.Push(stringConcat(L, L.GetTop()-retbottom, L.reg.Top()-1))
  74. return 1
  75. }
  76. func tableInsert(L *LState) int {
  77. tbl := L.CheckTable(1)
  78. nargs := L.GetTop()
  79. if nargs == 1 {
  80. L.RaiseError("wrong number of arguments")
  81. }
  82. if L.GetTop() == 2 {
  83. tbl.Append(L.Get(2))
  84. return 0
  85. }
  86. tbl.Insert(int(L.CheckInt(2)), L.CheckAny(3))
  87. return 0
  88. }
  89. //