Lua scripts and notes for programming within Minetest.

testfn.lua 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. local function split(str)
  2. -- should return single string, flat table of strings, or nil
  3. local ast = {}
  4. local prev, space = 0, str:find(" ", 0, true)
  5. local ret
  6. while space do
  7. ret = str:sub(prev + 1, space - 1)
  8. if #ret > 0 then
  9. table.insert(ast, ret)
  10. end
  11. prev = space
  12. space = str:find(" ", prev + 1, true)
  13. end
  14. ret = str:sub(prev + 1)
  15. if #ret > 0 then
  16. table.insert(ast, ret)
  17. end
  18. if #ast < 1 then
  19. return nil
  20. elseif #ast == 1 then
  21. return ast[1]
  22. else
  23. return ast
  24. end
  25. end
  26. local table_tostring
  27. local function parse(str)
  28. -- should return table with strings and tables, etc, or nil
  29. local ast = {}
  30. local open, close = str:find("(", 0, true), str:find(")", 0, true)
  31. local ret
  32. while open and close and open < close do
  33. --print("---" .. str:sub(1, open - 1))
  34. table.insert(ast, split(str:sub(1, open - 1)))
  35. --print(str:sub(open + 1))
  36. ret, str = parse(str:sub(open + 1))
  37. --print("RET", ret, ret[1], ret[2])
  38. --print(table_tostring(ast))
  39. --print(ret, "'"..str.."'", #ret, ret[1], ret[2])
  40. table.insert(ast, ret)
  41. --print(table_tostring(ast))
  42. --print("--------------")
  43. open, close = str:find("(", 0, true), str:find(")", 0, true)
  44. end
  45. --print(";;"..str)
  46. if close then
  47. --print(str:sub(1, close - 1))
  48. table.insert(ast, split(str:sub(1, close - 1)))
  49. ret = str:sub(close + 1)
  50. if #ast < 1 then
  51. return nil, ret
  52. elseif #ast == 1 then
  53. return ast[1], ret
  54. else
  55. return ast, ret
  56. end
  57. end
  58. if #ast < 1 then
  59. return nil
  60. elseif #ast == 1 then
  61. return ast[1]
  62. else
  63. return ast
  64. end
  65. end
  66. -- (echo (: "value" ($ name))) -- true/false depending on $name == "value"
  67. -- (while ($ name) (run command)) -- while $name run(command)
  68. -- fns = {
  69. -- print, =, if, for, while
  70. -- }
  71. --local table_tostring
  72. table_tostring = function(tab, depth)
  73. local str = ""
  74. depth = depth or 0
  75. if "table" == type(tab) then
  76. for k,v in pairs(tab) do
  77. str = str .. table_tostring(k, depth) .. " =\n"
  78. str = str .. table_tostring(v, depth + 1) .. "\n"
  79. end
  80. return str
  81. else
  82. return string.rep(" ", depth) .. tostring(tab) .. " (" .. type(tab):sub(1, 1) .. ")"
  83. end
  84. end
  85. local ast, extra = parse("(echo (: \"value\" ($ name)))")
  86. --local ast, extra = parse("(while ($ name) (run command))")
  87. --local ast, extra = parse("b b (c c)")
  88. print(table_tostring(ast))
  89. print(extra)