LuaDataFormatter.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "precompiled.h"
  2. #include "LuaDataFormatter.h"
  3. #include <Rocket/Core/Lua/Interpreter.h>
  4. #include <Rocket/Core/Log.h>
  5. namespace Rocket {
  6. namespace Core {
  7. namespace Lua {
  8. LuaDataFormatter::LuaDataFormatter(const String& name) : Rocket::Controls::DataFormatter(name), ref_FormatData(LUA_NOREF)
  9. {
  10. }
  11. LuaDataFormatter::~LuaDataFormatter()
  12. {
  13. //empty
  14. }
  15. void LuaDataFormatter::FormatData(Rocket::Core::String& formatted_data, const Rocket::Core::StringList& raw_data)
  16. {
  17. if(ref_FormatData == LUA_NOREF || ref_FormatData == LUA_REFNIL)
  18. {
  19. Log::Message(Log::LT_ERROR, "In LuaDataFormatter: There is no value assigned to the \"FormatData\" variable.");
  20. return;
  21. }
  22. lua_State* L = Interpreter::GetLuaState();
  23. PushDataFormatterFunctionTable(L); // push the table where the function resides
  24. lua_rawgeti(L,-1,ref_FormatData); //push the function
  25. if(lua_type(L,-1) != LUA_TFUNCTION)
  26. {
  27. Log::Message(Log::LT_ERROR, "In LuaDataFormatter: The value for the FormatData variable must be a function. You passed in a %s.", lua_typename(L,lua_type(L,-1)));
  28. return;
  29. }
  30. lua_newtable(L); //to hold raw_data
  31. int tbl = lua_gettop(L);
  32. for(unsigned int i = 0; i < raw_data.size(); i++)
  33. {
  34. lua_pushstring(L,raw_data[i].CString());
  35. lua_rawseti(L,tbl,i);
  36. }
  37. Interpreter::ExecuteCall(1,1); //1 parameter (the table), 1 result (a string)
  38. //top of the stack should be the return value
  39. if(lua_type(L,-1) != LUA_TSTRING)
  40. {
  41. Log::Message(Log::LT_ERROR, "In LuaDataFormatter: the return value of FormatData must be a string. You returned a %s.", lua_typename(L,lua_type(L,-1)));
  42. return;
  43. }
  44. formatted_data = String(lua_tostring(L,-1));
  45. }
  46. void LuaDataFormatter::PushDataFormatterFunctionTable(lua_State* L)
  47. {
  48. lua_getglobal(L,"LUADATAFORMATTERFUNCTIONS");
  49. if(lua_isnoneornil(L,-1))
  50. {
  51. lua_newtable(L);
  52. lua_setglobal(L,"LUADATAFORMATTERFUNCTIONS");
  53. lua_pop(L,1); //pop the unsucessful getglobal
  54. lua_getglobal(L,"LUADATAFORMATTERFUNCTIONS");
  55. }
  56. }
  57. }
  58. }
  59. }