convert.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Package convert provides functions for converting to and from Lua structures
  2. package convert
  3. import (
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sort"
  9. "strings"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/xyproto/gluamapper"
  12. lua "github.com/xyproto/gopher-lua"
  13. "github.com/xyproto/jpath"
  14. )
  15. var errToMap = errors.New("could not represent Lua structure table as a map")
  16. // PprintToWriter outputs more informative information than the memory location.
  17. // Attempt to extract and print the values of the given lua.LValue.
  18. // Does not add a newline at the end.
  19. func PprintToWriter(w io.Writer, value lua.LValue) {
  20. switch v := value.(type) {
  21. case *lua.LTable:
  22. t := (*lua.LTable)(v)
  23. // Even if t.Len() is 0, the table may be full of elements
  24. m, isAnArray, err := Table2interfaceMapGlua(t)
  25. if err != nil {
  26. // log.Info("try: for k,v in pairs(t) do pprint(k,v) end")
  27. // Could not convert to a map
  28. fmt.Fprint(w, v)
  29. return
  30. }
  31. if isAnArray {
  32. // A map which is really an array (arrays in Lua are maps)
  33. var buf bytes.Buffer
  34. buf.WriteString("{")
  35. // Order the map
  36. length := len(m)
  37. for i := 1; i <= length; i++ {
  38. // gluamapper uses float64 for all numbers?
  39. if val, ok := m[float64(i)]; ok {
  40. buf.WriteString(fmt.Sprintf("%#v", val))
  41. if i != length {
  42. // Output a comma for every element except the last one
  43. buf.WriteString(", ")
  44. }
  45. } else if val, ok := m[i]; ok {
  46. buf.WriteString(fmt.Sprintf("%#v", val))
  47. if i != length {
  48. // Output a comma for every element except the last one
  49. buf.WriteString(", ")
  50. }
  51. } else {
  52. // Unrecognized type of array or map, just return the sprintf representation
  53. buf.Reset()
  54. buf.WriteString(fmt.Sprintf("%v", m))
  55. buf.WriteTo(w)
  56. return
  57. }
  58. }
  59. buf.WriteString("}")
  60. buf.WriteTo(w)
  61. return
  62. }
  63. if len(m) == 0 {
  64. // An empty map
  65. fmt.Fprint(w, "{}")
  66. return
  67. }
  68. // Convert the map to a string
  69. // First extract the keys, and sort them
  70. var mapKeys []string
  71. stringMap := make(map[string]string)
  72. for k, v := range m {
  73. keyString := fmt.Sprintf("%#v", k)
  74. keyString = strings.TrimPrefix(keyString, "\"")
  75. keyString = strings.TrimSuffix(keyString, "\"")
  76. valueString := fmt.Sprintf("%#v", v)
  77. mapKeys = append(mapKeys, keyString)
  78. stringMap[keyString] = valueString
  79. }
  80. sort.Strings(mapKeys)
  81. // Then loop over the keys and build a string
  82. var sb strings.Builder
  83. sb.WriteString("{")
  84. for i, keyString := range mapKeys {
  85. if i != 0 {
  86. sb.WriteString(", ")
  87. }
  88. valueString := stringMap[keyString]
  89. sb.WriteString(keyString + "=" + valueString)
  90. }
  91. sb.WriteString("}")
  92. // Then replace "[]interface {}" with nothing and output the string
  93. s := strings.ReplaceAll(sb.String(), "[]interface {}", "")
  94. fmt.Fprint(w, s)
  95. case *lua.LFunction:
  96. if v.Proto != nil {
  97. // Extended information about the function
  98. fmt.Fprint(w, v.Proto)
  99. } else {
  100. fmt.Fprint(w, v)
  101. }
  102. case *lua.LUserData:
  103. if jfile, ok := v.Value.(*jpath.JFile); ok {
  104. fmt.Fprintln(w, v)
  105. fmt.Fprintf(w, "filename: %s\n", jfile.GetFilename())
  106. if data, err := jfile.JSON(); err == nil { // success
  107. fmt.Fprintf(w, "JSON data:\n%s", string(data))
  108. }
  109. } else {
  110. fmt.Fprint(w, v)
  111. }
  112. default:
  113. fmt.Fprint(w, v)
  114. }
  115. }
  116. // Arguments2buffer retrieves all the arguments given to a Lua function
  117. // and gather the strings in a buffer.
  118. func Arguments2buffer(L *lua.LState, addNewline bool) bytes.Buffer {
  119. var buf bytes.Buffer
  120. top := L.GetTop()
  121. // Add all the string arguments to the buffer
  122. for i := 1; i <= top; i++ {
  123. buf.WriteString(L.Get(i).String())
  124. if i != top {
  125. buf.WriteString(" ")
  126. }
  127. }
  128. if addNewline {
  129. buf.WriteString("\n")
  130. }
  131. return buf
  132. }
  133. // Strings2table converts a string slice to a Lua table
  134. func Strings2table(L *lua.LState, sl []string) *lua.LTable {
  135. table := L.NewTable()
  136. for _, element := range sl {
  137. table.Append(lua.LString(element))
  138. }
  139. return table
  140. }
  141. // Map2table converts a map[string]string to a Lua table
  142. func Map2table(L *lua.LState, m map[string]string) *lua.LTable {
  143. table := L.NewTable()
  144. for key, value := range m {
  145. L.RawSet(table, lua.LString(key), lua.LString(value))
  146. }
  147. return table
  148. }
  149. // ArrMaps2table converts a []map[string]lua.LValue to a Lua table
  150. func ArrMaps2table(L *lua.LState, maps []map[string]string) *lua.LTable {
  151. outer := L.NewTable()
  152. for _, m := range maps {
  153. inner := L.NewTable()
  154. for k, v := range m {
  155. L.RawSet(inner, lua.LString(k), lua.LString(v))
  156. }
  157. outer.Append(inner)
  158. }
  159. return outer
  160. }
  161. // LValueMaps2table converts a []map[string]lua.LValue to a Lua table
  162. func LValueMaps2table(L *lua.LState, maps []map[string]lua.LValue) *lua.LTable {
  163. outer := L.NewTable()
  164. for _, m := range maps {
  165. inner := L.NewTable()
  166. for k, v := range m {
  167. L.RawSet(inner, lua.LString(k), v)
  168. }
  169. outer.Append(inner)
  170. }
  171. return outer
  172. }
  173. // Table2map converts a Lua table to **one** of the following types, depending
  174. // on the content:
  175. //
  176. // map[string]string
  177. // map[string]int
  178. // map[int]string
  179. // map[int]int
  180. //
  181. // If no suitable keys and values are found, a nil interface is returned.
  182. // If several different types are found, it returns true.
  183. func Table2map(luaTable *lua.LTable, preferInt bool) (any, bool) {
  184. mapSS, mapSI, mapIS, mapII := Table2maps(luaTable)
  185. lss := len(mapSS)
  186. lsi := len(mapSI)
  187. lis := len(mapIS)
  188. lii := len(mapII)
  189. total := lss + lsi + lis + lii
  190. // Return the first map that has values
  191. if !preferInt {
  192. if lss > 0 {
  193. // log.Println(key, "STRING -> STRING map")
  194. return any(mapSS), lss < total
  195. } else if lsi > 0 {
  196. // log.Println(key, "STRING -> INT map")
  197. return any(mapSI), lsi < total
  198. } else if lis > 0 {
  199. // log.Println(key, "INT -> STRING map")
  200. return any(mapIS), lis < total
  201. } else if lii > 0 {
  202. // log.Println(key, "INT -> INT map")
  203. return any(mapII), lii < total
  204. }
  205. } else {
  206. if lii > 0 {
  207. // log.Println(key, "INT -> INT map")
  208. return any(mapII), lii < total
  209. } else if lis > 0 {
  210. // log.Println(key, "INT -> STRING map")
  211. return any(mapIS), lis < total
  212. } else if lsi > 0 {
  213. // log.Println(key, "STRING -> INT map")
  214. return any(mapSI), lsi < total
  215. } else if lss > 0 {
  216. // log.Println(key, "STRING -> STRING map")
  217. return any(mapSS), lss < total
  218. }
  219. }
  220. return nil, false
  221. }
  222. // Table2maps converts a Lua table to **all** of the following types,
  223. // depending on the content:
  224. //
  225. // map[string]string
  226. // map[string]int
  227. // map[int]string
  228. // map[int]int
  229. func Table2maps(luaTable *lua.LTable) (map[string]string, map[string]int, map[int]string, map[int]int) {
  230. // Initialize possible maps we want to convert to
  231. mapSS := make(map[string]string)
  232. mapSI := make(map[string]int)
  233. mapIS := make(map[int]string)
  234. mapII := make(map[int]int)
  235. var skey, svalue lua.LString
  236. var ikey, ivalue lua.LNumber
  237. var hasSkey, hasIkey, hasSvalue, hasIvalue bool
  238. luaTable.ForEach(func(tkey, tvalue lua.LValue) {
  239. // Convert the keys and values to strings or ints
  240. skey, hasSkey = tkey.(lua.LString)
  241. ikey, hasIkey = tkey.(lua.LNumber)
  242. svalue, hasSvalue = tvalue.(lua.LString)
  243. ivalue, hasIvalue = tvalue.(lua.LNumber)
  244. // Store the right keys and values in the right maps
  245. if hasSkey && hasSvalue {
  246. mapSS[skey.String()] = svalue.String()
  247. } else if hasSkey && hasIvalue {
  248. mapSI[skey.String()] = int(ivalue)
  249. } else if hasIkey && hasSvalue {
  250. mapIS[int(ikey)] = svalue.String()
  251. } else if hasIkey && hasIvalue {
  252. mapII[int(ikey)] = int(ivalue)
  253. }
  254. })
  255. return mapSS, mapSI, mapIS, mapII
  256. }
  257. // Table2interfaceMap converts a Lua table to a map[string]any
  258. // If values are also tables, they are also attempted converted to map[string]any
  259. func Table2interfaceMap(luaTable *lua.LTable) map[string]any {
  260. // Even if luaTable.Len() is 0, the table may be full of things
  261. // Initialize possible maps we want to convert to
  262. everything := make(map[string]any)
  263. var skey, svalue lua.LString
  264. var nkey, nvalue lua.LNumber
  265. var hasSkey, hasSvalue, hasNkey, hasNvalue bool
  266. luaTable.ForEach(func(tkey, tvalue lua.LValue) {
  267. // Convert the keys and values to strings or ints or maps
  268. skey, hasSkey = tkey.(lua.LString)
  269. nkey, hasNkey = tkey.(lua.LNumber)
  270. svalue, hasSvalue = tvalue.(lua.LString)
  271. nvalue, hasNvalue = tvalue.(lua.LNumber)
  272. secondTableValue, hasTvalue := tvalue.(*lua.LTable)
  273. // Store the right keys and values in the right maps
  274. if hasSkey && hasTvalue {
  275. // Recursive call if the value is another table that can be converted to a string->any map
  276. everything[skey.String()] = Table2interfaceMap(secondTableValue)
  277. } else if hasNkey && hasTvalue {
  278. floatKey := float64(nkey)
  279. intKey := int(nkey)
  280. // Use the int key if it's the same as the float representation
  281. if floatKey == float64(intKey) {
  282. // Recursive call if the value is another table that can be converted to a string->any map
  283. everything[fmt.Sprintf("%d", intKey)] = Table2interfaceMap(secondTableValue)
  284. } else {
  285. everything[fmt.Sprintf("%f", floatKey)] = Table2interfaceMap(secondTableValue)
  286. }
  287. } else if hasSkey && hasSvalue {
  288. everything[skey.String()] = svalue.String()
  289. } else if hasSkey && hasNvalue {
  290. floatVal := float64(nvalue)
  291. intVal := int(nvalue)
  292. // Use the int value if it's the same as the float representation
  293. if floatVal == float64(intVal) {
  294. everything[skey.String()] = intVal
  295. } else {
  296. everything[skey.String()] = floatVal
  297. }
  298. } else if hasNkey && hasSvalue {
  299. floatKey := float64(nkey)
  300. intKey := int(nkey)
  301. // Use the int key if it's the same as the float representation
  302. if floatKey == float64(intKey) {
  303. everything[fmt.Sprintf("%d", intKey)] = svalue.String()
  304. } else {
  305. everything[fmt.Sprintf("%f", floatKey)] = svalue.String()
  306. }
  307. } else if hasNkey && hasNvalue {
  308. var sk, sv string
  309. floatKey := float64(nkey)
  310. intKey := int(nkey)
  311. floatVal := float64(nvalue)
  312. intVal := int(nvalue)
  313. // Use the int key if it's the same as the float representation
  314. if floatKey == float64(intKey) {
  315. sk = fmt.Sprintf("%d", intKey)
  316. } else {
  317. sk = fmt.Sprintf("%f", floatKey)
  318. }
  319. // Use the int value if it's the same as the float representation
  320. if floatVal == float64(intVal) {
  321. sv = fmt.Sprintf("%d", intVal)
  322. } else {
  323. sv = fmt.Sprintf("%f", floatVal)
  324. }
  325. everything[sk] = sv
  326. } else {
  327. log.Warn("table2interfacemap: Unsupported type for map key. Value:", tvalue)
  328. }
  329. })
  330. return everything
  331. }
  332. // Table2interfaceMapGlua converts a Lua table to a map by using gluamapper.
  333. // If the map really is an array (all the keys are indices), return true.
  334. func Table2interfaceMapGlua(luaTable *lua.LTable) (retmap map[any]any, isArray bool, err error) {
  335. var (
  336. m = make(map[any]any)
  337. opt = gluamapper.Option{}
  338. indices []uint64
  339. i, length uint64
  340. )
  341. // Catch a problem that may occur when converting the map value with gluamapper.ToGoValue
  342. defer func() {
  343. if r := recover(); r != nil {
  344. retmap = m
  345. err = errToMap // Could not represent Lua structure table as a map
  346. return
  347. }
  348. }()
  349. // Do the actual conversion
  350. luaTable.ForEach(func(tkey, tvalue lua.LValue) {
  351. if i, isNum := tkey.(lua.LNumber); isNum {
  352. indices = append(indices, uint64(i))
  353. }
  354. // If tkey or tvalue is an LTable, give up
  355. m[gluamapper.ToGoValue(tkey, opt)] = gluamapper.ToGoValue(tvalue, opt)
  356. length++
  357. })
  358. // Report back as a map, not an array, if there are no elements
  359. if length == 0 {
  360. return m, false, nil
  361. }
  362. // Loop through every index that must be present in an array
  363. isAnArray := true
  364. for i = 1; i <= length; i++ {
  365. // The map must have this index in order to be an array
  366. hasIt := false
  367. for _, val := range indices {
  368. if val == i {
  369. hasIt = true
  370. break
  371. }
  372. }
  373. if !hasIt {
  374. isAnArray = false
  375. break
  376. }
  377. }
  378. return m, isAnArray, nil
  379. }