api.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. --global string containing all registered formspec pages as table data
  2. ezformmaker = {
  3. pages = {},
  4. --Set String for Form's Context
  5. set_string = function(self, string, value)
  6. self[string] = value
  7. end,
  8. --Get String for Form's Context
  9. get_string = function(self, string)
  10. return self[string]
  11. end
  12. }
  13. --Register a new form page
  14. function ezformmaker.register_form_page(formname, def)
  15. local name_convention_check = string.match(formname, "[%w_]+%:[%w_]+")
  16. assert(formname, "Formspec requires a name.")
  17. assert(name_convention_check, "Name \""..formname.."\" does not follow naming conventions: \"<foo>:<bar>\" or \":\" prefix required.")
  18. assert(def, "attempt to index local def a nil value for formspec \""..formname.."\".")
  19. assert(def.on_send_form, "def requires method \"on_send_form\" for formspec \""..formname.."\".")
  20. assert(def.on_receive_fields, "def requires method \"on_receive_fields\" for formspec \""..formname.."\".")
  21. assert(not ezformmaker.pages[formname], "attempt to register a form page that already exist. " .. dump(formname))
  22. ezformmaker.pages[formname] = def
  23. def.name = formname
  24. end
  25. --Show specific formpage to a player by name
  26. function ezformmaker.show_form_page(name, formname)
  27. -- Cancel function if something went wrong and write a error log explaining what happened
  28. if minetest.get_player_by_name(name) == nil then
  29. minetest.log("error", "Failed to send form to specified player, player \""..name.."\" is not online.")
  30. return
  31. elseif ezformmaker.pages[formname] == nil then
  32. minetest.log("error", "Invalid form page, formspec \""..formname.."\" doesn\'t exist.")
  33. return
  34. end
  35. local player = minetest.get_player_by_name(name)
  36. local form = ezformmaker.pages[formname].on_send_form(player)
  37. minetest.show_formspec(name, formname, form)
  38. end
  39. --Input Event Handler
  40. minetest.register_on_player_receive_fields(function(player, formname, fields)
  41. --Don't do anything if fields are empty
  42. if fields == nil then
  43. return
  44. end
  45. local name = player:get_player_name()
  46. local verified_form = nil
  47. local pages = ezformmaker.pages
  48. local page = nil
  49. if pages == nil then return else
  50. for k,v in pairs(pages) do
  51. if k == formname then
  52. verified_form = k
  53. page = ezformmaker.pages[formname]
  54. break
  55. end
  56. end
  57. end
  58. if verified_form == nil then
  59. return
  60. elseif verified_form == formname then
  61. --If form page exists, make sure to run it's unique recieve fields script
  62. return page.on_receive_fields(player, formname, fields)
  63. end
  64. end)