lua-users home
lua-l archive

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

I was doing something with chained callbacks, using recursive closures to call
each other using the C interface, and was seeing some odd seg faults. I created
some test code (attached), and got some weird results. The doubled output from
the recursive calls is particularly weird. Have I hit a language bug, or is there
something obvious about my code I'm missing?

My lua version is:

Lua 5.1.4  Copyright (C) 1994-2008, PUC-Rio

The exact build is whatever's current in Mint Linux.

#include <lua.h>
#include <lauxlib.h>

static int
recursive_closure(lua_State *L)
	fprintf(stderr, "Recursive call %d\n",
	    luaL_checkint(L, lua_upvalueindex(1)));

	if (!lua_isnoneornil(L, lua_upvalueindex(2))) {
		luaL_checktype(L, lua_upvalueindex(2), LUA_TFUNCTION);
		lua_pushvalue(L, lua_upvalueindex(2));
		lua_call(L, 1, 0);

static void
push_recursive_closure(lua_State *L, int i)
	fprintf(stderr, "Called %s(%p, %d)\n", __func__, L, i);
	lua_pushinteger(L, i);
	if (i > 0)
		push_recursive_closure(L, i-1);
	lua_pushcclosure(L, recursive_closure, i > 0 ? 2 : 1);

static int
getrclosure(lua_State *L)
	push_recursive_closure(L, luaL_checkint(L, 1));
	return 1;

luaopen_rclosure(lua_State *L)
	lua_pushcfunction(L, getrclosure);
	lua_setfield(L, LUA_GLOBALSINDEX, "rclosure");
	return 0;

Attachment: recurse.lua
Description: Binary data

Attachment: recurse_output
Description: Binary data