eval.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include "wrapper.h"
  3. #include <library/cpp/json/json_value.h>
  4. #include <util/system/mutex.h>
  5. class TLuaEval {
  6. public:
  7. TLuaEval();
  8. template <class C>
  9. inline TLuaEval& SetVars(const C& container) {
  10. for (auto& [k, v] : container) {
  11. SetVariable(k, v);
  12. }
  13. return *this;
  14. }
  15. inline TLuaEval& Parse(TStringBuf chunk) {
  16. ParseChunk(chunk);
  17. return *this;
  18. }
  19. void SetVariable(TZtStringBuf name, const NJson::TJsonValue& value);
  20. template <typename T>
  21. void SetUserdata(TZtStringBuf name, T&& userdata) {
  22. LuaState_.push_userdata(std::forward<T>(userdata));
  23. LuaState_.set_global(name.c_str());
  24. }
  25. TString EvalExpression(TStringBuf expression);
  26. TString EvalRaw(TStringBuf code);
  27. void ParseChunk(TStringBuf code);
  28. TString Preprocess(TStringBuf line);
  29. TString PreprocessOne(TStringBuf line);
  30. bool CheckEmptyStack();
  31. struct TExpression {
  32. TString Name;
  33. };
  34. TExpression Compile(TStringBuf expression);
  35. TExpression CompileFunction(TStringBuf expression);
  36. TExpression CompileRaw(TStringBuf body, const TString& name);
  37. TString DumpStack();
  38. TString EvalCompiled(const TExpression& compiled);
  39. void EvalCompiledRaw(const TExpression& compiled);
  40. bool EvalCompiledCondition(const TExpression& compiled);
  41. template <typename TNumber>
  42. TNumber EvalCompiledNumeric(const TExpression& compiled) {
  43. TGuard<TMutex> guard(LuaMutex_);
  44. RunExpressionLocked(guard, compiled);
  45. return LuaState_.pop_number<TNumber>();
  46. }
  47. private:
  48. TString GenerateName();
  49. TString Evaluate(const TString& name, const TString& body);
  50. void RunExpressionLocked(const TGuard<TMutex>& lock, const TExpression& compiled);
  51. TLuaStateHolder LuaState_;
  52. ui64 FunctionNameCounter_;
  53. TMutex LuaMutex_;
  54. };