code.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. --- Lua code execution functions.
  2. -- @module worldedit.code
  3. --- Executes `code` as a Lua chunk in the global namespace.
  4. -- @return An error message if the code fails, or nil on success.
  5. function worldedit.lua(code)
  6. local func, err = loadstring(code)
  7. if not func then -- Syntax error
  8. return err
  9. end
  10. local good, err = pcall(func)
  11. if not good then -- Runtime error
  12. return err
  13. end
  14. return nil
  15. end
  16. --- Executes `code` as a Lua chunk in the global namespace with the variable
  17. -- pos available, for each node in a region defined by positions `pos1` and
  18. -- `pos2`.
  19. -- @return An error message if the code fails, or nil on success.
  20. function worldedit.luatransform(pos1, pos2, code)
  21. pos1, pos2 = worldedit.sort_pos(pos1, pos2)
  22. local factory, err = loadstring("return function(pos) " .. code .. " end")
  23. if not factory then -- Syntax error
  24. return err
  25. end
  26. local func = factory()
  27. worldedit.keep_loaded(pos1, pos2)
  28. local pos = {x=pos1.x, y=0, z=0}
  29. while pos.x <= pos2.x do
  30. pos.y = pos1.y
  31. while pos.y <= pos2.y do
  32. pos.z = pos1.z
  33. while pos.z <= pos2.z do
  34. local good, err = pcall(func, pos)
  35. if not good then -- Runtime error
  36. return err
  37. end
  38. pos.z = pos.z + 1
  39. end
  40. pos.y = pos.y + 1
  41. end
  42. pos.x = pos.x + 1
  43. end
  44. return nil
  45. end