lib.lua 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. intllib = intllib or {}
  2. local INS_CHAR = "@"
  3. intllib.INSERTION_CHAR = INS_CHAR
  4. local escapes = {
  5. ["\\"] = "\\",
  6. ["n"] = "\n",
  7. ["s"] = " ",
  8. ["t"] = "\t",
  9. ["r"] = "\r",
  10. ["f"] = "\f",
  11. [INS_CHAR] = INS_CHAR..INS_CHAR,
  12. }
  13. local function unescape(str)
  14. local parts = {}
  15. local n = 1
  16. local function add(s)
  17. parts[n] = s
  18. n = n + 1
  19. end
  20. local start = 1
  21. while true do
  22. local pos = str:find("\\", start, true)
  23. if pos then
  24. add(str:sub(start, pos - 1))
  25. else
  26. add(str:sub(start))
  27. break
  28. end
  29. local c = str:sub(pos + 1, pos + 1)
  30. add(escapes[c] or c)
  31. start = pos + 2
  32. end
  33. return table.concat(parts)
  34. end
  35. local function find_eq(s)
  36. for slashes, pos in s:gmatch("([\\]*)=()") do
  37. if (slashes:len() % 2) == 0 then
  38. return pos - 1
  39. end
  40. end
  41. end
  42. function intllib.load_strings(filename)
  43. local file, err = io.open(filename, "r")
  44. if not file then
  45. return nil, err
  46. end
  47. local strings = {}
  48. for line in file:lines() do
  49. line = line:trim()
  50. if line ~= "" and line:sub(1, 1) ~= "#" then
  51. local pos = find_eq(line)
  52. if pos then
  53. local msgid = unescape(line:sub(1, pos - 1):trim())
  54. strings[msgid] = unescape(line:sub(pos + 1):trim())
  55. end
  56. end
  57. end
  58. file:close()
  59. return strings
  60. end