@@ -135,26 +135,55 @@ QJsonValue TMCPLuaBridge::executeLuaCode(const QString& luaCode, const QString&
135135 return QJsonValue (tr (" Failed to setup Lua output capture" ));
136136 }
137137
138- // Execute the user's code
139- int result = luaL_dostring (L, luaCode.toUtf8 ().constData ());
138+ // Execute the user's code using luaL_loadstring + lua_pcall to capture return values
139+ // (luaL_dostring uses lua_pcall with 0 return values, so we can't capture them)
140+ int stackBefore = lua_gettop (L);
141+ int loadResult = luaL_loadstring (L, luaCode.toUtf8 ().constData ());
140142
141143 QString resultStr;
142- if (result ) {
143- // Handle Lua error
144+ if (loadResult != 0 ) {
145+ // Syntax error in Lua code
144146 if (lua_gettop (L) > 0 ) {
145- resultStr = tr (" Lua Error: %1" ).arg (QString::fromUtf8 (lua_tostring (L, -1 )));
147+ resultStr = tr (" Lua Syntax Error: %1" ).arg (QString::fromUtf8 (lua_tostring (L, -1 )));
146148 lua_pop (L, 1 );
147149 } else {
148- resultStr = tr (" Unknown Lua error occurred" );
150+ resultStr = tr (" Unknown Lua syntax error occurred" );
149151 }
150152 } else {
151- // Get any return value
152- if (lua_gettop (L) > 0 ) {
153- QJsonValue returnValue = luaStackToJson (L, -1 );
154- if (!returnValue.isNull ()) {
155- resultStr += tr (" Return value: %1\n " ).arg (QJsonDocument (QJsonArray{returnValue}).toJson (QJsonDocument::Compact));
153+ // Execute the compiled chunk, requesting all return values
154+ int execResult = lua_pcall (L, 0 , LUA_MULTRET, 0 );
155+
156+ if (execResult != 0 ) {
157+ // Runtime error
158+ if (lua_gettop (L) > 0 ) {
159+ resultStr = tr (" Lua Error: %1" ).arg (QString::fromUtf8 (lua_tostring (L, -1 )));
160+ lua_pop (L, 1 );
161+ } else {
162+ resultStr = tr (" Unknown Lua error occurred" );
163+ }
164+ } else {
165+ // Get all return values
166+ int returnCount = lua_gettop (L) - stackBefore;
167+ if (returnCount > 0 ) {
168+ if (returnCount == 1 ) {
169+ QJsonValue returnValue = luaStackToJson (L, -1 );
170+ if (!returnValue.isNull ()) {
171+ if (returnValue.isString ()) {
172+ resultStr = returnValue.toString ();
173+ } else {
174+ resultStr = QJsonDocument (QJsonArray{returnValue}).toJson (QJsonDocument::Compact);
175+ }
176+ }
177+ } else {
178+ // Multiple return values - return as array
179+ QJsonArray returnArray;
180+ for (int i = -returnCount; i <= -1 ; ++i) {
181+ returnArray.append (luaStackToJson (L, i));
182+ }
183+ resultStr = QJsonDocument (returnArray).toJson (QJsonDocument::Compact);
184+ }
185+ lua_pop (L, returnCount);
156186 }
157- lua_pop (L, 1 );
158187 }
159188 }
160189
0 commit comments