view c/readLuaScript.c @ 0:73146cb10aa5

add some files
author Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp>
date Fri, 01 Feb 2013 03:07:15 +0900
parents
children e12fbdb2eac2
line wrap: on
line source

#include <lua.hpp>


/* 
 * Reference http://marupeke296.com/LUA_No2_Begin.html
*/
void printStack(lua_State *L)
{
	const int num = lua_gettop(L);
	if (num == 0) {
		printf("no stack\n");
		return;
	}
	for (int i= num; i>= 1; i--) {
		printf("%03d(%04d):",i, -num + i - 1);
		int type= lua_type(L, i);
		switch(type) {
		case LUA_TNIL:
			printf("NIL\n");
			break;
		case LUA_TBOOLEAN:
			printf("BOOLEAN %s\n",lua_toboolean(L,i)?"true":"false");
			break;
		case LUA_TLIGHTUSERDATA:
			printf("LIGHTUSERDATA\n");
			break;
		case LUA_TNUMBER:
			printf("NUMBER %f\n", lua_tonumber(L,i));
			break;
		case LUA_TSTRING:
			printf("STRING %s\n", lua_tostring(L, i));
			break;
		case LUA_TTABLE:
			printf("TABLE\n");
			break;
		case LUA_TFUNCTION:
			printf("FUNCTION\n");
			break;
		case LUA_TUSERDATA:
			printf("USERDATA\n");
			break;
		case LUA_TTHREAD:
			printf("THERAD\n");
			break;
		}
	}
	printf("------------------\n");
}

int funcC(lua_State *L) 
{
	return 0;
}

int main(int argc, char *argv[])
{
	lua_State *L = luaL_newstate();
	lua_register(L, "funcC", &funcC);
	if (luaL_dofile(L, "testlib.lua")) {
		printf("%s\n", lua_tostring(L, lua_gettop(L)));
		return -1;
	}
	lua_getglobal(L,"add");
	lua_pushnumber(L, 2);
	lua_pushnumber(L, 3);
	printStack(L);
	/* 
	 * lua_pcall function
	 * @param lua_State
	 * @param number of argument value
	 * @param number of return value
	 * @param error handle stack ID
	 */
	if (lua_pcall(L, 2, 1, 0)) {
		printf("%s\n",lua_tostring(L, lua_gettop(L)));
		lua_close(L);
		return -1;
	}
	printStack(L);

	/* get return value */
	int add_res = (int)lua_tonumber(L, 1);
	printf("add(2,3) = %d\n",add_res);

	/* remove stack data */
	int num = lua_gettop(L);
	lua_pop(L, num);
	lua_close(L);

	return 0;
}