lua-users home
lua-l archive

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


On 14 Feb 2014, at 15:32, Thijs Schreijer <thijs@thijsschreijer.nl> wrote:

> Exactly, in this case the module table contains 20-25 capitalized constants. So if someone using the module has a typo in his code, I want it to throw an error instead of a silent 'nil' value.

Is the C code really that bad? See very verbose example below

Thanks,
Kevin

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

static int createModuleTable(lua_State *l) {
	lua_newtable(l);

	int i;
	for(i=1;i!=11;++i) {
		lua_pushinteger(l, i*i);
		lua_rawseti(l, -2, i);
	}

	return 1;
}

static int eone_index(lua_State *l) {
	lua_settop(l, 2);
	luaL_checktype(l, 1, LUA_TTABLE);

	//any value is acceptable for a key except nil
	//and the lua_gettable will error on nil
	//so don't need to check 2nd arg

	lua_pushvalue(l, 2);
	lua_rawget(l, 1);
	if(lua_type(l, -1) == LUA_TNIL) {
		return luaL_error(l, "Attempt to access nil entry '%s'",
		 luaL_tolstring(l, 2, NULL));
	}
	return 1;
}

static int eone_setup(lua_State *l) {
	lua_settop(l, 1);
	luaL_checktype(l, 1, LUA_TTABLE);

	//It's a programming error to call this on a table
	//with a metatable
	assert(lua_getmetatable(l, 1) == 0);

	//metatable
	lua_newtable(l);
	lua_pushcfunction(l, eone_index);
	lua_setfield(l, -2, "__index");
	lua_setmetatable(l, -2);

	return 1;
}

int luaopen_protectdemo(lua_State *l) {
	lua_settop(l, 0);

	lua_pushcfunction(l, eone_setup);
	createModuleTable(l);
	lua_call(l, 1, 1);

	return 1;
}