view C++/LuaeTable.cpp @ 225:e01ee0c72c43

Luae: begin refactoring of Luae
author David Demelier <markand@malikania.fr>
date Fri, 09 May 2014 17:12:25 +0200
parents
children
line wrap: on
line source

/*
 * LuaeTable.cpp -- Lua table helpers
 *
 * Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "LuaeTable.h"

void LuaeTable::create(lua_State *L, int nrec, int narr)
{
	LUAE_STACK_CHECKBEGIN(L);

	lua_createtable(L, nrec, narr);

	LUAE_STACK_CHECKEND(L, - 1);
}

int LuaeTable::type(lua_State *L, int idx, const std::string &name)
{
	int type;

	LUAE_STACK_CHECKBEGIN(L);

	lua_getfield(L, idx, name.c_str());
	type = lua_type(L, -1);
	lua_pop(L, 1);

	LUAE_STACK_CHECKEQUALS(L);

	return type;
}

void LuaeTable::read(lua_State *L, int idx, ReadFunction func)
{
	LUAE_STACK_CHECKBEGIN(L);

	lua_pushnil(L);

	if (idx < 0)
		--idx;

	while (lua_next(L, idx)) {
		func(L, lua_type(L, -2), lua_type(L, -1));
		lua_pop(L, 1);
	}

	LUAE_STACK_CHECKEQUALS(L);
}

int LuaeTable::ref(lua_State *L, int idx, int type, const std::string &name)
{
	int ref = LUA_REFNIL;

	lua_getfield(L, idx, name.c_str());

	if (lua_type(L, -1) == type) {
		lua_pushvalue(L, -1);
		ref = luaL_ref(L, LUA_REGISTRYINDEX);
	}

	lua_pop(L, 1);

	return ref;
}