Monday, February 9, 2015

Lua stack dump (WRONG CASE)

void _dumpStack(lua_State* L, const char* func, int line)
{
int top = lua_gettop(L);
printf("(%s,%d) top=%d\n", func, line, top);
for (int i = 0; i < top; i++) {
int positive = top - i;
int negative = -(i + 1);
int type = lua_type(L, positive);
const char* typeName = lua_typename(L, type);
const char* value = lua_tostring(L, positive); // danger!!! numbers on the Lua stack will be replaced with string
printf("%d/%d: type=%s value=%s\n", positive, negative, typeName, value);
}
}
This is very simple Lua stack dumper. It extracts all element values by using lua_tostring whatever the types is not a string. It looks work well, but the problem is that lua_tostring overwrites values in the stack by string version.

One of correct code is below. The programmer always needed to take a step to ensure their correct types when accessing the Lua stack.

void _dumpStack(lua_State* L, const char* func, int line)
{
int top = lua_gettop(L);
printf("(%s,%d) top=%d\n", func, line, top);
for (int i = 0; i < top; i++) {
int positive = top - i;
int negative = -(i + 1);
int type = lua_type(L, positive);
int typeN = lua_type(L, negative);
assert(type == typeN);
const char* typeName = lua_typename(L, type);
printf("%d/%d: type=%s", positive, negative, typeName);
switch (type) {
case LUA_TNUMBER:
printf(" value=%f", lua_tonumber(L, positive));
break;
case LUA_TSTRING:
printf(" value=%s", lua_tostring(L, positive));
break;
case LUA_TFUNCTION:
if (lua_iscfunction(L, positive)) {
printf(" C:%p", lua_tocfunction(L, positive));
}
break;
}
printf("\n");
}
}

No comments:

Post a Comment