lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Hi there,
>
> I am currently experiencing unpleasant segfaults when recursively
> traversing Lua tables. This is the Lua function whose return value I'd
> like to traverse:
>

>     void walk (lua_State *L, int idx) {
>         lua_pushnil(L);
>
>         printf("idx=%i\n", idx);

In the recursion, at this point, idx is -1. After the lua_pushnil,
stack element -1 (the top of the stack is nil). The subsequent call
to lua_next(L, idx) attempts to do a "next" operation on nil.

The Lua API does not protect you from type errors like this unless
you enable API checking (see the Lua FAQ on the Wiki "Why does my
program segfault?" for a pointer on how to enable this.)

My suggestion is that you use absolute (base-relative) instead of
negative (top-relative) stack indexes.

>     key: 4
>     idx=-1
>     key: 0
>     val: 0 (number)
>     Segmentation fault (core dumped)
>