Lua 5.2.1 stack corruption

Posted by ThomasWatts on Fri 28 Sep 2012 11:42 PM — 4 posts, 18,176 views.

USA #0
Has anyone ever encountered bad stack corruption in Lua, any version?
I am reaching the end of my rope as I can not find where or how the stack is getting corrupted.
Of course with the style of messages below I'm just assuming it's stack corruption. Any help would be appreciated.

Error Message:

Sep 28, 19:32:04|BUG|Segmentation Violation
Sep 28, 19:32:04|BUG|Error 2 loading Lua startup file ../lib/Main.lua:
 ../lib/DB.lua:33: bad argument #2 to 'dir' (number expected, got string)
stack traceback:
        [C]: in function 'dir'
        ../lib/DB.lua:33: in function 'loadDirectory'
        ../lib/Main.lua:49: in main chunk


DB.lua line 33:

	local tbl = { kernel.dir(dir) };


kernel.dir function:

static int EXL_get_directory(lua_State *L) {
	int nArgs = 0;
	DIR *d;
	struct dirent *entry = NULL;
	const char *buf = luaL_checkstring(L, 1);
	char dir_str[SHORT_STR_LENGTH * 2]; //256
	nArgs = sprintf(dir_str, "%s", buf);
	if( nArgs <= 0 ) {
		return luaL_error(L, "Bad argument #1 to kernel.dir, string expected.");
	}
	d = opendir(dir_str);
	if( d == NULL ) {
		return luaL_error(L, "Cannot open directory %s for access.", dir_str);
	}
	nArgs = 0;
	while( (entry = readdir(d)) != NULL ) {
		if( entry->d_name == NULL ) {
			break;
		} else if( entry->d_name[0] == '.' ) {
			continue;
		} else {
			lua_pushstring(L, entry->d_name);
			nArgs++;
		}
	}
	closedir(d);
	return nArgs;
}


This is not a request for help regarding the above function, but just a general query of horrible experiences with Lua and how the problems were fixed/worked around.
Amended on Fri 28 Sep 2012 11:43 PM by ThomasWatts
Australia Forum Administrator #1
How many entries are in the directory?

The default Lua stack size is 20, and it looks like you might possibly be doing more than 20 x lua_pushstring.

I suggest making a table and adding entries to that. That way you only use one stack spot (the table) and the table can have any number of entries. That is how utils.readdir in MUSHclient works.
USA #2
Didn't know 20 was the default stack size. I'll change that function over to a table and see how that works out.
USA #3
Finally tracked the problem down. While moving more code around between files I started getting errors about redeclarations of structs and funcitons.

opendir, readdir, etc were already present in services.c (holdover from Smaug 1.4a) as well as in main.h.

Mingw did not define these functions a few years ago, but now include in the dirent.h header file.

Removed these functions from the files, used the built-in functions and bam! problem gone.

So, short story made shorter, the problem was not actually in Lua, but in the C functions.