* @brief Runs mqtt(frame) in a disposable engine and returns the published payload. */
| 607 | * @brief Runs mqtt(frame) in a disposable engine and returns the published payload. |
| 608 | */ |
| 609 | QString MQTT::PublisherScriptEditor::runScript(const QString& code, |
| 610 | int language, |
| 611 | const QByteArray& frame, |
| 612 | QString& errorOut) |
| 613 | { |
| 614 | if (code.trimmed().isEmpty()) { |
| 615 | errorOut = tr("Script is empty"); |
| 616 | return {}; |
| 617 | } |
| 618 | |
| 619 | if (language == SerialStudio::Lua) { |
| 620 | lua_State* L = luaL_newstate(); |
| 621 | if (!L) { |
| 622 | errorOut = tr("Lua engine error"); |
| 623 | return {}; |
| 624 | } |
| 625 | |
| 626 | static const luaL_Reg kSafeLibs[] = { |
| 627 | { "_G", luaopen_base}, |
| 628 | { "table", luaopen_table}, |
| 629 | {"string", luaopen_string}, |
| 630 | { "math", luaopen_math}, |
| 631 | { "os", luaopen_os}, |
| 632 | { nullptr, nullptr} |
| 633 | }; |
| 634 | |
| 635 | for (const luaL_Reg* lib = kSafeLibs; lib->func; ++lib) { |
| 636 | luaL_requiref(L, lib->name, lib->func, 1); |
| 637 | lua_pop(L, 1); |
| 638 | } |
| 639 | |
| 640 | DataModel::installLuaCompat(L); |
| 641 | |
| 642 | const QByteArray utf8 = code.toUtf8(); |
| 643 | if (luaL_dostring(L, utf8.constData()) != LUA_OK) { |
| 644 | errorOut = tr("Error: %1").arg(QString::fromUtf8(lua_tostring(L, -1))); |
| 645 | lua_close(L); |
| 646 | return {}; |
| 647 | } |
| 648 | |
| 649 | lua_getglobal(L, "mqtt"); |
| 650 | if (!lua_isfunction(L, -1)) { |
| 651 | lua_close(L); |
| 652 | errorOut = tr("mqtt() is not defined"); |
| 653 | return {}; |
| 654 | } |
| 655 | |
| 656 | lua_pushlstring(L, frame.constData(), static_cast<size_t>(frame.size())); |
| 657 | if (lua_pcall(L, 1, 1, 0) != LUA_OK) { |
| 658 | errorOut = tr("Error: %1").arg(QString::fromUtf8(lua_tostring(L, -1))); |
| 659 | lua_close(L); |
| 660 | return {}; |
| 661 | } |
| 662 | |
| 663 | QString out; |
| 664 | if (lua_isstring(L, -1)) { |
| 665 | size_t len = 0; |
| 666 | const char* d = lua_tolstring(L, -1, &len); |
nothing calls this directly
no test coverage detected