Skip to content

Commit 43bc3dd

Browse files
fix(luajava): correct stack imbalance in local_import
1 parent a2207e0 commit 43bc3dd

File tree

1 file changed

+27
-22
lines changed

1 file changed

+27
-22
lines changed

nexlua/native/src/main/cpp/lib_import.c

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -139,58 +139,63 @@ static int local_import(lua_State *L, int idx) {
139139
return 0;
140140
}
141141
// local require
142-
int require_err = luaJ_require(L, idx);
142+
int require_top = lua_gettop(L);
143+
int require_err = luaJ_require(L, require_top);
143144
if (require_err == LUA_OK) {
144145
return 1;
145146
} else {
146-
require_err = lua_gettop(L);
147+
require_err = require_top + 1;
148+
if (require_err != lua_gettop(L)) {
149+
lua_replace(L, require_err);
150+
lua_settop(L, require_top + 1);
151+
}
147152
}
148153
// import class
149154
int top = lua_gettop(L);
150155
jstring string = ToString(name);
151156
int result = (*env)->CallStaticIntMethod(env, com_luajava_LuaJava,
152157
com_luajava_LuaJava_bindClass, (jlong) L, string);
153158
DeleteString(string);
154-
if (!checkIfError(env, L) && result) {
159+
if (!(*env)->ExceptionOccurred(env) && result) {
155160
char *simpleName = strdup(get_simple_name(name));
156161
if (!simpleName) luaJ_error_memory(L);
157162
lua_pushvalue(L, -1);
158163
lua_setglobal(L, simpleName);
159164
free(simpleName);
160165
return 1;
161-
} else if (require_err) {
162-
lua_pushnil(L);
163-
lua_setglobal(L, JAVA_GLOBAL_THROWABLE);
164-
lua_settop(L, require_err);
166+
} else {
167+
(*env)->ExceptionClear(env);
165168
}
169+
lua_settop(L, require_err);
166170
return lua_error(L);
167171
}
168172

169173
/* Modules and functions */
170174
int import(lua_State *L) {
171-
int type = lua_type(L, 1);
172-
if (type == LUA_TSTRING) {
173-
return local_import(L, 1);
174-
}
175-
if (type == LUA_TTABLE) {
176-
lua_pushnil(L);
177-
while (lua_next(L, 1) != 0) {
178-
if (lua_type(L, -1) == LUA_TSTRING) {
179-
int top = lua_gettop(L);
180-
const char *str = lua_tostring(L, -1);
181-
lua_pushstring(L, str);
182-
local_import(L, -1);
183-
lua_settop(L, top);
175+
switch (lua_type(L, -1)) {
176+
case LUA_TSTRING:
177+
return local_import(L, -1);
178+
case LUA_TTABLE: {
179+
int top = lua_gettop(L);
180+
lua_Integer len = lua_objlen(L, -1);
181+
for (lua_Integer i = 1; i <= len; i++) {
182+
lua_rawgeti(L, -1, i);
183+
if (lua_isstring(L, -1)) {
184+
local_import(L, -1);
185+
lua_settop(L, top);
186+
} else {
187+
lua_pop(L, 1);
188+
}
184189
}
185-
lua_pop(L, 1);
190+
return 0;
186191
}
187-
return 0;
188192
}
189193
return luaL_typerror(L, 1, "string or table");
190194
}
191195

192196
/* Register the module */
193197
REGISTER_MODULE(import, luaopen_import);
198+
194199
int luaopen_import(lua_State *L) {
195200
// import function
196201
lua_pushcfunction(L, import);

0 commit comments

Comments
 (0)