static inline int _cloneNoTable(lua_State *L, const int idx, 
	lua_State *L_, const int r_lv ) { 
	int ret_= 1; switch(lua_type(L, idx ) ) { 
		case LUA_TSTRING: { 
			size_t l; const char *s= lua_tolstring(L, idx, &l ); 
			lua_pushlstring(L_, s, l ); 
		} break; 
		case LUA_TNUMBER: 
		lua_pushnumber(L_, lua_tonumber(L, idx ) ); 
		break; 
		case LUA_TLIGHTUSERDATA: 
		lua_pushlightuserdata(L_, lua_touserdata(L, idx ) ); 
		break; 
		case LUA_TBOOLEAN: 
		lua_pushboolean(L_, lua_toboolean(L, idx ) ); 
		break; 
		case LUA_TUSERDATA: { // userdata 的 meta 暂时不能拷贝 
			const size_t l= lua_objlen(L, idx ); 
			memmove(lua_newuserdata(L_, l ), 
				lua_touserdata(L, idx ), l ); if(0) //屏蔽 meta 处理 
			if(lua_getmetatable(L, idx ) ) { 
				const int k= _cloneRecursion(L, lua_gettop(L ), L_, 
					((0<= r_lv )? r_lv: -1 ) ); lua_pop(L, 1 ); 
				if((0<= r_lv )&& lua_istable(L_, -1 )&& (0< k ) ) 
					printf("%*.s__{%3d}\n", (r_lv- 1 )* 2, "", k ); 
				lua_setmetatable(L_, -2 ); 
			} 
		} break; 
		case LUA_TFUNCTION: 
		if(lua_iscfunction(L, idx ) ) { 
			int j= 1; lua_CFunction f= lua_tocfunction(L, idx ); 
			for(j= 1; UPVALUE_MAX>= j; ++j ) { 
				//设置函数的 upvalue 
				if(!lua_getupvalue(L, idx, j ) ) break; 
				_cloneRecursion(L, lua_gettop(L ), L_, 
					((0<= r_lv )? (r_lv+ 1 ): -1 ) ); lua_pop(L, 1 ); 
			} lua_pushcclosure(L_, f, j- 1 ); 
		} else 
		{ int j= 1; DUMP_CB ud; memset(&ud, 0, sizeof(ud ) ); 
			lua_pushvalue(L, idx ); lua_dump(L, writer_CB, &ud ); 
			if(ud.p ) { //载入函数到新的栈 
				lua_load(L_, reader_CB, &ud, (char * )0 ); free(ud.p ); 
			} lua_pop(L, 1 ); 
			for(j= 1; UPVALUE_MAX>= j; ++j ) { 
				//设置函数的 upvalue 
				if(!lua_getupvalue(L, idx, j ) ) break; 
printf("upvalue %d\n", j ); 
				_cloneRecursion(L, lua_gettop(L ), L_, 
					((0<= r_lv )? (r_lv+ 1 ): -1 ) ); lua_pop(L, 1 ); 
				lua_setupvalue(L_, -2, j ); 
			} 
		} break; 
		case LUA_TNIL: 
		lua_pushnil(L_ ); 
		break; 
		case LUA_TNONE: 
		case LUA_TTHREAD: //?
		default: 
		ret_= 0; break; 
	} 
	return ret_; 
} 
Ejemplo n.º 2
0
static void
lua_push_method_global(lua_State* state, const char* name, size_t length, lua_CFunction fn) {
	lua_pushcclosure(state, fn, 0);
	lua_setlglobal(state, name, length);
}
Ejemplo n.º 3
0
static void aux_lines (lua_State *L, int idx, int toclose) {
  lua_pushvalue(L, idx);
  lua_pushboolean(L, toclose);  /* close/not close file when finished */
  lua_pushcclosure(L, io_readline, 2);
}
Ejemplo n.º 4
0
/**
 * Set environment table for the given code closure.
 *
 * Before:
 *         | code closure | <- top
 *         |      ...     |
 *
 * After:
 *         | code closure | <- top
 *         |      ...     |
 * */
static void
ngx_http_lua_set_by_lua_env(lua_State *L, ngx_http_request_t *r, size_t nargs,
        ngx_http_variable_value_t *args)
{
    /*  set nginx request pointer to current lua thread's globals table */
    lua_pushlightuserdata(L, r);
    lua_setglobal(L, GLOBALS_SYMBOL_REQUEST);

    /**
     * we want to create empty environment for current script
     *
     * setmetatable({}, {__index = _G})
     *
     * if a function or symbol is not defined in our env, __index will lookup
     * in the global env.
     *
     * all variables created in the script-env will be thrown away at the end
     * of the script run.
     * */
    lua_newtable(L);    /*  new empty environment aka {} */

    /*  override 'print' function */
    lua_pushcfunction(L, ngx_http_lua_print);
    lua_setfield(L, -2, "print");

    /*  {{{ initialize ngx.* namespace */
    lua_newtable(L);    /*  ngx.* */

    lua_newtable(L);    /*  .arg table aka {} */

    lua_newtable(L);    /*  the metatable for new param table */
    lua_pushinteger(L, nargs);    /*  1st upvalue: argument number */
    lua_pushlightuserdata(L, args);    /*  2nd upvalue: pointer to arguments */

    lua_pushcclosure(L, ngx_http_lua_param_get, 2);
        /*  binding upvalues to __index meta-method closure */

    lua_setfield(L, -2, "__index");
    lua_setmetatable(L, -2);    /*  tie the metatable to param table */

    lua_setfield(L, -2, "arg");    /*  set ngx.arg table */

    /* {{{ register reference maps */
    lua_newtable(L);    /* ngx.var */

    lua_newtable(L); /* metatable for ngx.var */
    lua_pushcfunction(L, ngx_http_lua_var_get);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, ngx_http_lua_var_set);
    lua_setfield(L, -2, "__newindex");
    lua_setmetatable(L, -2);

    lua_setfield(L, -2, "var");
    /*  }}} */

#if (NGX_PCRE)
    /* {{{ ngx.re table */

    lua_newtable(L);    /* .re */

    lua_pushcfunction(L, ngx_http_lua_ngx_re_match);
    lua_setfield(L, -2, "match");

    lua_pushcfunction(L, ngx_http_lua_ngx_re_gmatch);
    lua_setfield(L, -2, "gmatch");

    lua_pushcfunction(L, ngx_http_lua_ngx_re_sub);
    lua_setfield(L, -2, "sub");

    lua_pushcfunction(L, ngx_http_lua_ngx_re_gsub);
    lua_setfield(L, -2, "gsub");

    lua_setfield(L, -2, "re");

    /* }}} */
#endif /* NGX_PCRE */

    lua_pushcfunction(L, ngx_http_lua_ngx_escape_uri);
    lua_setfield(L, -2, "escape_uri");

    lua_pushcfunction(L, ngx_http_lua_ngx_unescape_uri);
    lua_setfield(L, -2, "unescape_uri");

    lua_pushcfunction(L, ngx_http_lua_ngx_quote_sql_str);
    lua_setfield(L, -2, "quote_sql_str");

    lua_pushcfunction(L, ngx_http_lua_ngx_decode_base64);
    lua_setfield(L, -2, "decode_base64");

    lua_pushcfunction(L, ngx_http_lua_ngx_encode_base64);
    lua_setfield(L, -2, "encode_base64");

    lua_pushcfunction(L, ngx_http_lua_ngx_md5_bin);
    lua_setfield(L, -2, "md5_bin");

    lua_pushcfunction(L, ngx_http_lua_ngx_md5);
    lua_setfield(L, -2, "md5");

    lua_pushcfunction(L, ngx_http_lua_ngx_time);
    lua_setfield(L, -2, "get_now_ts"); /* deprecated */

    lua_pushcfunction(L, ngx_http_lua_ngx_utctime);
    lua_setfield(L, -2, "utctime");

    lua_pushcfunction(L, ngx_http_lua_ngx_localtime);
    lua_setfield(L, -2, "get_now"); /* deprecated */

    lua_pushcfunction(L, ngx_http_lua_ngx_time);
    lua_setfield(L, -2, "time");

    lua_pushcfunction(L, ngx_http_lua_ngx_localtime);
    lua_setfield(L, -2, "localtime");

    lua_pushcfunction(L, ngx_http_lua_ngx_today);
    lua_setfield(L, -2, "get_today"); /* deprecated */

    lua_pushcfunction(L, ngx_http_lua_ngx_today);
    lua_setfield(L, -2, "today");

    lua_pushcfunction(L, ngx_http_lua_ngx_http_time);
    lua_setfield(L, -2, "http_time");

	lua_pushcfunction(L, ngx_http_lua_ngx_parse_http_time);
    lua_setfield(L, -2, "parse_http_time");

    lua_pushcfunction(L, ngx_http_lua_ngx_cookie_time);
    lua_setfield(L, -2, "cookie_time");

    lua_pushcfunction(L, ngx_http_lua_ngx_log);
    lua_setfield(L, -2, "log");

    ngx_http_lua_inject_log_consts(L);

    /* ngx. getter and setter */
    lua_createtable(L, 0, 2); /* metatable for .ngx */
    lua_pushcfunction(L, ngx_http_lua_ngx_get);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, ngx_http_lua_ngx_set);
    lua_setfield(L, -2, "__newindex");
    lua_setmetatable(L, -2);

    lua_setfield(L, -2, "ngx");
    /*  }}} */

    /*  {{{ make new env inheriting main thread's globals table */
    lua_newtable(L);    /*  the metatable for the new env */
    lua_pushvalue(L, LUA_GLOBALSINDEX);
    lua_setfield(L, -2, "__index");
    lua_setmetatable(L, -2);    /*  setmetatable({}, {__index = _G}) */
    /*  }}} */

    lua_setfenv(L, -2);    /*  set new running env for the code closure */
}
Ejemplo n.º 5
0
int cache_parse_lua(server *srv, connection *con, plugin_data *p, buffer *fn) {
	lua_State *L;
	int ret = -1;
	buffer *b;

	b = buffer_init();
	/* push the lua file to the interpreter and see what happends */
	L = luaL_newstate();
	luaL_openlibs(L);

	/* register functions */
	lua_register(L, "md5", f_crypto_md5);
	lua_register(L, "file_mtime", f_file_mtime);
	lua_register(L, "file_isreg", f_file_isreg);
	lua_register(L, "file_isdir", f_file_isreg);
	lua_register(L, "dir_files", f_dir_files);

#ifdef USE_MEMCACHED
	lua_pushlightuserdata(L, p->conf.memc);
	lua_pushcclosure(L, f_memcache_get_long, 1);
	lua_setglobal(L, "memcache_get_long");

	lua_pushlightuserdata(L, p->conf.memc);
	lua_pushcclosure(L, f_memcache_get_string, 1);
	lua_setglobal(L, "memcache_get_string");

	lua_pushlightuserdata(L, p->conf.memc);
	lua_pushcclosure(L, f_memcache_exists, 1);
	lua_setglobal(L, "memcache_exists");
#endif

	/* register CGI environment */
	lua_newtable(L);
	{
		int header_tbl = lua_gettop(L);

		c_to_lua_push(L, header_tbl, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
		c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
		c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path));
		c_to_lua_push(L, header_tbl, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir));
		if (!buffer_string_is_empty(con->request.pathinfo)) {
			c_to_lua_push(L, header_tbl, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
		}

		c_to_lua_push(L, header_tbl, CONST_STR_LEN("CWD"), CONST_BUF_LEN(p->basedir));
		c_to_lua_push(L, header_tbl, CONST_STR_LEN("BASEURL"), CONST_BUF_LEN(p->baseurl));
	}
	lua_setglobal(L, "request");

	/* register GET parameter */
	lua_newtable(L);
	{
		int get_tbl = lua_gettop(L);

		buffer_copy_buffer(b, con->uri.query);
		cache_export_get_params(L, get_tbl, b);
		buffer_reset(b);
	}
	lua_setglobal(L, "get");

	/* 2 default constants */
	lua_pushinteger(L, 0);
	lua_setglobal(L, "CACHE_HIT");

	lua_pushinteger(L, 1);
	lua_setglobal(L, "CACHE_MISS");

	/* load lua program */
	ret = luaL_loadfile(L, fn->ptr);
	if (0 != ret) {
		log_error_write(srv, __FILE__, __LINE__, "sbsS",
			"failed loading cml_lua script",
			fn,
			":",
			lua_tostring(L, -1));
		goto error;
	}

	if (lua_pcall(L, 0, 1, 0)) {
		log_error_write(srv, __FILE__, __LINE__, "sbsS",
			"failed running cml_lua script",
			fn,
			":",
			lua_tostring(L, -1));
		goto error;
	}

	/* get return value */
	ret = (int)lua_tointeger(L, -1);
	lua_pop(L, 1);

	/* fetch the data from lua */
	lua_to_c_get_string(L, "trigger_handler", p->trigger_handler);

	if (0 == lua_to_c_get_string(L, "output_contenttype", b)) {
		response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(b));
	}

	if (ret == 0) {
		/* up to now it is a cache-hit, check if all files exist */

		int curelem;
		time_t mtime = 0;

		if (!lua_to_c_is_table(L, "output_include")) {
			log_error_write(srv, __FILE__, __LINE__, "s",
				"output_include is missing or not a table");
			ret = -1;

			goto error;
		}

		lua_getglobal(L, "output_include");
		curelem = lua_gettop(L);

		/* HOW-TO build a etag ?
		 * as we don't just have one file we have to take the stat()
		 * from all base files, merge them and build the etag from
		 * it later.
		 *
		 * The mtime of the content is the mtime of the freshest base file
		 *
		 * */

		lua_pushnil(L);  /* first key */
		while (lua_next(L, curelem) != 0) {
			/* key' is at index -2 and value' at index -1 */

			if (lua_isstring(L, -1)) {
				const char *s = lua_tostring(L, -1);
				struct stat st;
				int fd;

				/* the file is relative, make it absolute */
				if (s[0] != '/') {
					buffer_copy_buffer(b, p->basedir);
					buffer_append_string(b, lua_tostring(L, -1));
				} else {
					buffer_copy_string(b, lua_tostring(L, -1));
				}

				fd = stat_cache_open_rdonly_fstat(srv, con, b, &st);
				if (fd < 0) {
					/* stat failed */

					switch(errno) {
					case ENOENT:
						/* a file is missing, call the handler to generate it */
						if (!buffer_string_is_empty(p->trigger_handler)) {
							ret = 1; /* cache-miss */

							log_error_write(srv, __FILE__, __LINE__, "s",
									"a file is missing, calling handler");

							break;
						} else {
							/* handler not set -> 500 */
							ret = -1;

							log_error_write(srv, __FILE__, __LINE__, "s",
									"a file missing and no handler set");

							break;
						}
						break;
					default:
						break;
					}
				} else {
					chunkqueue_append_file_fd(con->write_queue, b, fd, 0, st.st_size);
					if (st.st_mtime > mtime) mtime = st.st_mtime;
				}
			} else {
				/* not a string */
				ret = -1;
				log_error_write(srv, __FILE__, __LINE__, "s",
						"not a string");
				break;
			}

			lua_pop(L, 1);  /* removes value'; keeps key' for next iteration */
		}

		lua_settop(L, curelem - 1);

		if (ret == 0) {
			data_string *ds;
			char timebuf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")];

			con->file_finished = 1;

			ds = (data_string *)array_get_element(con->response.headers, "Last-Modified");
			if (0 == mtime) mtime = time(NULL); /* default last-modified to now */

			/* no Last-Modified specified */
			if (NULL == ds) {

				strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime));

				response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), timebuf, sizeof(timebuf) - 1);
				ds = (data_string *)array_get_element(con->response.headers, "Last-Modified");
				force_assert(NULL != ds);
			}

			if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, ds->value)) {
				/* ok, the client already has our content,
				 * no need to send it again */

				chunkqueue_reset(con->write_queue);
				ret = 0; /* cache-hit */
			}
		} else {
			chunkqueue_reset(con->write_queue);
		}
	}

	if (ret == 1 && !buffer_string_is_empty(p->trigger_handler)) {
		/* cache-miss */
		buffer_copy_buffer(con->uri.path, p->baseurl);
		buffer_append_string_buffer(con->uri.path, p->trigger_handler);

		buffer_copy_buffer(con->physical.path, p->basedir);
		buffer_append_string_buffer(con->physical.path, p->trigger_handler);

		chunkqueue_reset(con->write_queue);
	}

error:
	lua_close(L);

	buffer_free(b);

	return ret /* cache-error */;
}
Ejemplo n.º 6
0
static int lzstream_lines(lua_State *L) {
    lzstream_check(L, 1, LZ_INFLATE);
    lua_settop(L, 1);
    lua_pushcclosure(L, lzstream_readline, 1);
    return 1;
}
Ejemplo n.º 7
0
int luax_register_type(lua_State *L, love::Type *type, ...)
{
	type->init();

	// Get the place for storing and re-using instantiated love types.
	luax_getregistry(L, REGISTRY_OBJECTS);

	// Create registry._loveobjects if it doesn't exist yet.
	if (!lua_istable(L, -1))
	{
		lua_newtable(L);
		lua_replace(L, -2);

		// Create a metatable.
		lua_newtable(L);

		// metatable.__mode = "v". Weak userdata values.
		lua_pushliteral(L, "v");
		lua_setfield(L, -2, "__mode");

		// setmetatable(newtable, metatable)
		lua_setmetatable(L, -2);

		// registry._loveobjects = newtable
		lua_setfield(L, LUA_REGISTRYINDEX, "_loveobjects");
	}
	else
		lua_pop(L, 1);

	luaL_newmetatable(L, type->getName());

	// m.__index = m
	lua_pushvalue(L, -1);
	lua_setfield(L, -2, "__index");

	// setup gc
	lua_pushcfunction(L, w__gc);
	lua_setfield(L, -2, "__gc");

	// Add equality
	lua_pushcfunction(L, w__eq);
	lua_setfield(L, -2, "__eq");

	// Add tostring function.
	lua_pushstring(L, type->getName());
	lua_pushcclosure(L, w__tostring, 1);
	lua_setfield(L, -2, "__tostring");

	// Add type
	lua_pushstring(L, type->getName());
	lua_pushcclosure(L, w__type, 1);
	lua_setfield(L, -2, "type");

	// Add typeOf
	lua_pushcfunction(L, w__typeOf);
	lua_setfield(L, -2, "typeOf");

	// Add release
	lua_pushcfunction(L, w__release);
	lua_setfield(L, -2, "release");

	va_list fs;
	va_start(fs, type);
	for (const luaL_Reg *f = va_arg(fs, const luaL_Reg *); f; f = va_arg(fs, const luaL_Reg *))
		luax_setfuncs(L, f);
	va_end(fs);

	lua_pop(L, 1); // Pops metatable.
	return 0;
}
Ejemplo n.º 8
0
static int sector_get(lua_State *L)
{
	sector_t *sector = *((sector_t **)luaL_checkudata(L, 1, META_SECTOR));
	enum sector_e field = luaL_checkoption(L, 2, sector_opt[0], sector_opt);

	if (!sector)
	{
		if (field == sector_valid) {
			lua_pushboolean(L, 0);
			return 1;
		}
		return luaL_error(L, "accessed sector_t doesn't exist anymore.");
	}

	switch(field)
	{
	case sector_valid: // valid
		lua_pushboolean(L, 1);
		return 1;
	case sector_floorheight:
		lua_pushinteger(L, sector->floorheight);
		return 1;
	case sector_ceilingheight:
		lua_pushinteger(L, sector->ceilingheight);
		return 1;
	case sector_floorpic: { // floorpic
		levelflat_t *levelflat;
		INT16 i;
		for (i = 0, levelflat = levelflats; i != sector->floorpic; i++, levelflat++)
			;
		lua_pushlstring(L, levelflat->name, 8);
		return 1;
	}
	case sector_ceilingpic: { // ceilingpic
		levelflat_t *levelflat;
		INT16 i;
		for (i = 0, levelflat = levelflats; i != sector->ceilingpic; i++, levelflat++)
			;
		lua_pushlstring(L, levelflat->name, 8);
		return 1;
	}
	case sector_lightlevel:
		lua_pushinteger(L, sector->lightlevel);
		return 1;
	case sector_special:
		lua_pushinteger(L, sector->special);
		return 1;
	case sector_tag:
		lua_pushinteger(L, sector->tag);
		return 1;
	case sector_thinglist: // thinglist
		lua_pushcfunction(L, lib_iterateSectorThinglist);
		LUA_PushUserdata(L, sector->thinglist, META_MOBJ);
		lua_pushcclosure(L, sector_iterate, 2); // push lib_iterateSectorThinglist and sector->thinglist as upvalues for the function
		return 1;
	case sector_heightsec: // heightsec - fake floor heights
		if (sector->heightsec < 0)
			return 0;
		LUA_PushUserdata(L, &sectors[sector->heightsec], META_SECTOR);
		return 1;
	case sector_camsec: // camsec - camera clipping heights
		if (sector->camsec < 0)
			return 0;
		LUA_PushUserdata(L, &sectors[sector->camsec], META_SECTOR);
		return 1;
	case sector_ffloors: // ffloors
		lua_pushcfunction(L, lib_iterateSectorFFloors);
		LUA_PushUserdata(L, sector->ffloors, META_FFLOOR);
		lua_pushcclosure(L, sector_iterate, 2); // push lib_iterateFFloors and sector->ffloors as upvalues for the function
		return 1;
	}
	return 0;
}
Ejemplo n.º 9
0
TOLUA_API void tolua_open(lua_State *L)
{
	int top = lua_gettop(L);
	lua_pushstring(L, "tolua_opened");
	lua_rawget(L, LUA_REGISTRYINDEX);
	if (!lua_isboolean(L, -1))
	{
		lua_pushstring(L, "tolua_opened");
		lua_pushboolean(L, 1);
		lua_rawset(L, LUA_REGISTRYINDEX);

#ifndef LUA_VERSION_NUM /* only prior to lua 5.1 */
		/* create peer object table */
		lua_pushstring(L, "tolua_peers");
		lua_newtable(L);
		/* make weak key metatable for peers indexed by userdata object */
		lua_newtable(L);
		lua_pushliteral(L, "__mode");
		lua_pushliteral(L, "k");
		lua_rawset(L, -3);			 /* stack: string peers mt */
		lua_setmetatable(L, -2); /* stack: string peers */
		lua_rawset(L, LUA_REGISTRYINDEX);
#endif

		/* create object ptr -> udata mapping table */
		lua_pushstring(L, "tolua_ubox");
		lua_newtable(L);
		/* make weak value metatable for ubox table to allow userdata to be
     garbage-collected */
		lua_newtable(L);
		lua_pushliteral(L, "__mode");
		lua_pushliteral(L, "v");
		lua_rawset(L, -3);			 /* stack: string ubox mt */
		lua_setmetatable(L, -2); /* stack: string ubox */
		lua_rawset(L, LUA_REGISTRYINDEX);

		lua_pushstring(L, "tolua_super");
		lua_newtable(L);
		lua_rawset(L, LUA_REGISTRYINDEX);
		lua_pushstring(L, "tolua_gc");
		lua_newtable(L);
		lua_rawset(L, LUA_REGISTRYINDEX);

		/* create gc_event closure */
		lua_pushstring(L, "tolua_gc_event");
		lua_pushstring(L, "tolua_gc");
		lua_rawget(L, LUA_REGISTRYINDEX);
		lua_pushstring(L, "tolua_super");
		lua_rawget(L, LUA_REGISTRYINDEX);
		lua_pushcclosure(L, class_gc_event, 2);
		lua_rawset(L, LUA_REGISTRYINDEX);

		tolua_newmetatable(L, "tolua_commonclass");

		tolua_module(L, NULL, 0);
		tolua_beginmodule(L, NULL);
		tolua_module(L, "tolua", 0);
		tolua_beginmodule(L, "tolua");
		tolua_function(L, "type", tolua_bnd_type);
		tolua_function(L, "takeownership", tolua_bnd_takeownership);
		tolua_function(L, "releaseownership", tolua_bnd_releaseownership);
		tolua_function(L, "cast", tolua_bnd_cast);
		tolua_function(L, "inherit", tolua_bnd_inherit);
#ifdef LUA_VERSION_NUM /* lua 5.1 */
		tolua_function(L, "setpeer", tolua_bnd_setpeer);
		tolua_function(L, "getpeer", tolua_bnd_getpeer);
#endif

		tolua_endmodule(L);
		tolua_endmodule(L);
	}
	lua_settop(L, top);
}
Ejemplo n.º 10
0
int main(int argc, char** argv)
{
	td_bin_allocator bin_alloc;
	const char *homedir;
	int res, rc, i;
	lua_State* L;

	td_init_portable();

#if !defined(TD_STANDALONE)
	if (NULL == (homedir = td_init_homedir()))
		return 1;
#else
	homedir = "";
#endif

	td_bin_allocator_init(&bin_alloc);

	L = lua_newstate(td_lua_alloc, &bin_alloc);
	if (!L)
		exit(1);

	lua_atpanic(L, on_lua_panic);

	luaL_openlibs(L);

	tundra_open(L);

#if defined(TD_STANDALONE)
	/* this is equivalent to table.insert(package.loaders, 1, td_load_embedded_file) */

	/* get the function */
	lua_getglobal(L, "table");
	lua_getfield(L, -1, "insert");
	lua_remove(L, -2);
	assert(!lua_isnil(L, -1));

	/* arg1: the package.loaders table */
	lua_getglobal(L, "package");
	lua_getfield(L, -1, "loaders");
	lua_remove(L, -2);
	assert(!lua_isnil(L, -1));

	lua_pushinteger(L, 1); /* arg 2 */
	lua_pushcfunction(L, td_load_embedded_file); /* arg 3 */

	lua_call(L, 3, 0);
#endif

	/* setup package.path */
	{
		char ppath[1024];
		snprintf(ppath, sizeof(ppath),
			"%s" TD_PATHSEP_STR "scripts" TD_PATHSEP_STR "?.lua;"
			"%s" TD_PATHSEP_STR "lua" TD_PATHSEP_STR "etc" TD_PATHSEP_STR "?.lua", homedir, homedir);
		lua_getglobal(L, "package");
		assert(LUA_TTABLE == lua_type(L, -1));
		lua_pushstring(L, ppath);
		lua_setfield(L, -2, "path");
	}

	/* push our error handler on the stack now (before the chunk to run) */
	lua_pushcclosure(L, get_traceback, 0);

	switch (luaL_loadbuffer(L, boot_snippet, sizeof(boot_snippet)-1, "boot_snippet"))
	{
	case LUA_ERRMEM:
		td_croak("out of memory");
		return 1;
	case LUA_ERRSYNTAX:
		td_croak("syntax error\n%s\n", lua_tostring(L, -1));
		return 1;
	}

	lua_newtable(L);
	lua_pushstring(L, homedir);
	lua_rawseti(L, -2, 1);

	for (i=1; i<argc; ++i)
	{
		lua_pushstring(L, argv[i]);
		lua_rawseti(L, -2, i+1);
	}

	{
		double t2;
		script_call_t1 = td_timestamp();
		res = lua_pcall(L, /*narg:*/1, /*nres:*/0, /*errorfunc:*/ -3);
		t2 = td_timestamp();
		if (global_tundra_stats)
			printf("total time spent in tundra: %.4fs\n", t2 - script_call_t1);
	}

	if (res == 0)
	{
		rc = global_tundra_exit_code;
	}
	else
	{
		fprintf(stderr, "%s\n", lua_tostring(L, -1));
		rc = 1;
	}

	lua_close(L);

	td_bin_allocator_cleanup(&bin_alloc);

	return rc;
}
Ejemplo n.º 11
0
void register_lua_funcs( lua_State* L )
{
#define FUNC( X )			\
  lua_pushcfunction( L, luaCB_##X );	\
  lua_setglobal( L, #X )

    FUNC(shoot);
    FUNC(sleep);
    FUNC(cls);
    FUNC(set_console_layout);
    FUNC(set_console_autoredraw);
    FUNC(console_redraw);

    lua_pushlightuserdata( L, action_push_click );
    lua_pushcclosure( L, luaCB_keyfunc, 1 );
    lua_setglobal( L, "click" );

    lua_pushlightuserdata( L, action_push_press );
    lua_pushcclosure( L, luaCB_keyfunc, 1 );
    lua_setglobal( L, "press" );

    lua_pushlightuserdata( L, action_push_release );
    lua_pushcclosure( L, luaCB_keyfunc, 1 );
    lua_setglobal( L, "release" );

    FUNC(get_av96);
    FUNC(get_av96);
    FUNC(get_bv96);
    FUNC(get_day_seconds);
    FUNC(get_disk_size);
    FUNC(get_dof);
    FUNC(get_far_limit);
    FUNC(get_free_disk_space);
    FUNC(get_focus);
    FUNC(get_hyp_dist);
    FUNC(get_iso_market);
    FUNC(get_iso_mode);
    FUNC(get_iso_real);
    FUNC(get_jpg_count);
    FUNC(get_near_limit);
    FUNC(get_prop);
    FUNC(get_raw_count);
    FUNC(get_raw_nr);
    FUNC(get_raw);
    FUNC(get_sv96);
    FUNC(get_tick_count);
    FUNC(get_tv96);
    FUNC(get_user_av_id);
    FUNC(get_user_av96);
    FUNC(get_user_tv_id);
    FUNC(get_user_tv96);
    FUNC(get_vbatt);
    FUNC(get_zoom);
    FUNC(get_exp_count);
    FUNC(get_flash_params_count);
    FUNC(get_parameter_data);

    FUNC(set_av96_direct);
    FUNC(set_av96);
    FUNC(set_focus);
    FUNC(set_iso_mode);
    FUNC(set_iso_real);
    FUNC(set_led);
    FUNC(set_nd_filter);
    FUNC(set_prop);
    FUNC(set_raw_nr);
    FUNC(set_raw);
    FUNC(set_sv96);
    FUNC(set_tv96_direct);
    FUNC(set_tv96);
    FUNC(set_user_av_by_id_rel);
    FUNC(set_user_av_by_id);
    FUNC(set_user_av96);
    FUNC(set_user_tv_by_id_rel);
    FUNC(set_user_tv_by_id);
    FUNC(set_user_tv96);
    FUNC(set_zoom_speed);
    FUNC(set_zoom_rel);
    FUNC(set_zoom);

    FUNC(wait_click);
    FUNC(is_pressed);
    FUNC(is_key);
#ifdef CAM_HAS_JOGDIAL
    FUNC(wheel_right);
    FUNC(wheel_left);
#endif
    FUNC(md_get_cell_diff);
    FUNC(md_detect_motion);
    FUNC(autostarted);
    FUNC(get_autostart);
    FUNC(set_autostart);
    FUNC(get_usb_power);
    FUNC(exit_alt);
    FUNC(shut_down);
    FUNC(print_screen);

    FUNC(get_focus_mode);
    FUNC(get_propset);
    FUNC(get_zoom_steps);
    FUNC(get_drive_mode);
    FUNC(get_flash_mode);
    FUNC(get_shooting);
    FUNC(get_flash_ready);
    FUNC(get_IS_mode);
    FUNC(set_ev);
    FUNC(get_ev);
    FUNC(get_orientation_sensor);
    FUNC(get_nd_present);
    FUNC(get_movie_status);
    FUNC(set_movie_status);

    FUNC(get_histo_range);
    FUNC(shot_histo_enable);
    FUNC(play_sound);
    FUNC(get_temperature);
    FUNC(peek);
    FUNC(poke);
    FUNC(bitand);
    FUNC(bitor);
    FUNC(bitxor);
    FUNC(bitshl);
    FUNC(bitshri);
    FUNC(bitshru);
    FUNC(bitnot);

    FUNC(get_time);

    FUNC(get_buildinfo);
    FUNC(get_mode);

    FUNC(set_raw_develop);
    // NOTE these functions normally run in the spytask.
    // called from lua they will run from kbd task instead
    FUNC(raw_merge_start);
    FUNC(raw_merge_add_file);
    FUNC(raw_merge_end);
    FUNC(set_backlight);
    FUNC(set_aflock);
#ifdef OPT_CURVES
    FUNC(set_curve_state);
#endif
// get levent definition by name or id, nil if not found
    FUNC(get_levent_def);
// get levent definition by index, nil if out of range
    FUNC(get_levent_def_by_index);
// get levent index from name or ID
    FUNC(get_levent_index);
    FUNC(post_levent_to_ui);
    FUNC(post_levent_for_npt);
    FUNC(set_levent_active);
    FUNC(set_levent_script_mode);

    FUNC(set_capture_mode);
    FUNC(set_capture_mode_canon);
    FUNC(is_capture_mode_valid);

    FUNC(set_record);

    FUNC(switch_mode_usb);

#ifdef OPT_LUA_CALL_NATIVE
    FUNC(call_event_proc);
    FUNC(call_func_ptr);
#endif
    FUNC(reboot);
#ifdef CAM_CHDK_PTP
    FUNC(read_usb_msg);
    FUNC(write_usb_msg);
    luaL_dostring(L,"function usb_msg_table_to_string(t)"
                  " local v2s=function(v)"
                  " local t=type(v)"
                  " if t=='string' then return v end"
                  " if t=='number' or t=='boolean' or t=='nil' then return tostring(v) end"
                  " return '' end"
                  " local r=''"
                  " for k,v in pairs(t) do"
                  " local s,vs=''"
                  " if type(v)=='table' then"
                  " for i=1,table.maxn(v) do"
                  " s=s..'\\t'..v2s(v[i]) end"
                  " else"
                  " vs=v2s(v)"
                  " if #vs then s=s..'\\t'..vs end"
                  " end"
                  " vs=v2s(k)"
                  " if #vs>0 and #s>0 then r=r..vs..s..'\\n' end"
                  " end"
                  " return r"
                  " end");

#endif
}
Ejemplo n.º 12
0
static void auxopen (lua_State *L, const char *name,
                     lua_CFunction f, lua_CFunction u) {
  lua_pushcfunction(L, u);
  lua_pushcclosure(L, f, 1);
  lua_setfield(L, -2, name);
}
Ejemplo n.º 13
0
static void register_getargs (char *argv[]) {
  lua_pushuserdata(L, argv);
  lua_pushcclosure(L, l_getargs, 1);
  lua_setglobal(L, "getargs");
}
static inline int getCClosureN(lua_State* luaSt, void* v, int n)
{
    lua_pushcclosure(luaSt, (lua_CFunction) v, n);
    return 1;
}
Ejemplo n.º 15
0
static handler_t magnet_attract(server *srv, connection *con, plugin_data *p, buffer *name) {
	lua_State *L;
	int lua_return_value = -1;
	int errfunc;
	/* get the script-context */


	L = script_cache_get_script(srv, con, p->cache, name);

	if (lua_isstring(L, -1)) {
		log_error_write(srv, __FILE__, __LINE__,
				"sbss",
				"loading script",
				name,
				"failed:",
				lua_tostring(L, -1));

		lua_pop(L, 1);

		assert(lua_gettop(L) == 0); /* only the function should be on the stack */

		con->http_status = 500;
		con->mode = DIRECT;

		return HANDLER_FINISHED;
	}

	lua_pushstring(L, "lighty.srv");
	lua_pushlightuserdata(L, srv);
	lua_settable(L, LUA_REGISTRYINDEX); /* registery[<id>] = srv */

	lua_pushstring(L, "lighty.con");
	lua_pushlightuserdata(L, con);
	lua_settable(L, LUA_REGISTRYINDEX); /* registery[<id>] = con */

	lua_atpanic(L, magnet_atpanic);

	/**
	 * we want to create empty environment for our script
	 *
	 * setmetatable({}, {__index = _G})
	 *
	 * if a function, symbol is not defined in our env, __index will lookup
	 * in the global env.
	 *
	 * all variables created in the script-env will be thrown
	 * away at the end of the script run.
	 */
	lua_newtable(L); /* my empty environment aka {}              (sp += 1) */

	/* we have to overwrite the print function */
	lua_pushcfunction(L, magnet_print);                       /* (sp += 1) */
	lua_setfield(L, -2, "print"); /* -1 is the env we want to set(sp -= 1) */

	/**
	 * lighty.request[] has the HTTP-request headers
	 * lighty.content[] is a table of string/file
	 * lighty.header[] is a array to set response headers
	 */

	lua_newtable(L); /* lighty.*                                 (sp += 1) */

	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_newtable(L); /* the meta-table for the request-table     (sp += 1) */
	lua_pushcfunction(L, magnet_reqhdr_get);                  /* (sp += 1) */
	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
	lua_pushcfunction(L, magnet_reqhdr_pairs);                /* (sp += 1) */
	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
	lua_setmetatable(L, -2); /* tie the metatable to request     (sp -= 1) */
	lua_setfield(L, -2, "request"); /* content = {}              (sp -= 1) */

	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_newtable(L); /* the meta-table for the request-table     (sp += 1) */
	lua_pushcfunction(L, magnet_env_get);                     /* (sp += 1) */
	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
	lua_pushcfunction(L, magnet_env_set);                     /* (sp += 1) */
	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
	lua_pushcfunction(L, magnet_env_pairs);                   /* (sp += 1) */
	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
	lua_setmetatable(L, -2); /* tie the metatable to request     (sp -= 1) */
	lua_setfield(L, -2, "env"); /* content = {}                  (sp -= 1) */

	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_newtable(L); /* the meta-table for the request-table     (sp += 1) */
	lua_pushcfunction(L, magnet_cgi_get);                     /* (sp += 1) */
	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
	lua_pushcfunction(L, magnet_cgi_set);                     /* (sp += 1) */
	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
	lua_pushcfunction(L, magnet_cgi_pairs);                   /* (sp += 1) */
	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
	lua_setmetatable(L, -2); /* tie the metatable to req_env     (sp -= 1) */
	lua_setfield(L, -2, "req_env"); /* content = {}              (sp -= 1) */

	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_newtable(L); /* the meta-table for the request-table     (sp += 1) */
	lua_pushcfunction(L, magnet_status_get);                  /* (sp += 1) */
	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
	lua_pushcfunction(L, magnet_status_set);                  /* (sp += 1) */
	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
	lua_pushcfunction(L, magnet_status_pairs);                /* (sp += 1) */
	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
	lua_setmetatable(L, -2); /* tie the metatable to request     (sp -= 1) */
	lua_setfield(L, -2, "status"); /* content = {}               (sp -= 1) */

	/* add empty 'content' and 'header' tables */
	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_setfield(L, -2, "content"); /* content = {}              (sp -= 1) */

	lua_newtable(L); /*  {}                                      (sp += 1) */
	lua_setfield(L, -2, "header"); /* header = {}                (sp -= 1) */

	lua_pushinteger(L, MAGNET_RESTART_REQUEST);
	lua_setfield(L, -2, "RESTART_REQUEST");

	lua_pushcfunction(L, magnet_stat);                        /* (sp += 1) */
	lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */

	lua_setfield(L, -2, "lighty"); /* lighty.*                   (sp -= 1) */

	/* override the default pairs() function to our __pairs capable version */
	lua_getglobal(L, "pairs"); /* push original pairs()          (sp += 1) */
	lua_pushcclosure(L, magnet_pairs, 1);
	lua_setfield(L, -2, "pairs");                             /* (sp -= 1) */

	lua_newtable(L); /* the meta-table for the new env           (sp += 1) */
	lua_pushvalue(L, LUA_GLOBALSINDEX);                       /* (sp += 1) */
	lua_setfield(L, -2, "__index"); /* { __index = _G }          (sp -= 1) */
	lua_setmetatable(L, -2); /* setmetatable({}, {__index = _G}) (sp -= 1) */


	lua_setfenv(L, -2); /* on the stack should be a modified env (sp -= 1) */

	errfunc = push_traceback(L, 0);
	if (lua_pcall(L, 0, 1, errfunc)) {
		lua_remove(L, errfunc);
		log_error_write(srv, __FILE__, __LINE__,
			"ss",
			"lua_pcall():",
			lua_tostring(L, -1));
		lua_pop(L, 1); /* remove the error-msg and the function copy from the stack */

		assert(lua_gettop(L) == 1); /* only the function should be on the stack */

		con->http_status = 500;
		con->mode = DIRECT;

		return HANDLER_FINISHED;
	}
	lua_remove(L, errfunc);

	/* we should have the function-copy and the return value on the stack */
	assert(lua_gettop(L) == 2);

	if (lua_isnumber(L, -1)) {
		/* if the ret-value is a number, take it */
		lua_return_value = (int)lua_tonumber(L, -1);
	}
	lua_pop(L, 1); /* pop the ret-value */

	magnet_copy_response_header(srv, con, p, L);

	if (lua_return_value > 99) {
		con->http_status = lua_return_value;
		con->file_finished = 1;

		/* try { ...*/
		if (0 == setjmp(exceptionjmp)) {
			magnet_attach_content(srv, con, p, L);
			if (!chunkqueue_is_empty(con->write_queue)) {
				con->mode = p->id;
			}
		} else {
			/* } catch () { */
			con->http_status = 500;
			con->mode = DIRECT;
		}

		assert(lua_gettop(L) == 1); /* only the function should be on the stack */

		/* we are finished */
		return HANDLER_FINISHED;
	} else if (MAGNET_RESTART_REQUEST == lua_return_value) {
		assert(lua_gettop(L) == 1); /* only the function should be on the stack */

		return HANDLER_COMEBACK;
	} else {
		assert(lua_gettop(L) == 1); /* only the function should be on the stack */

		return HANDLER_GO_ON;
	}
}
Ejemplo n.º 16
0
int luax_register_type(lua_State *L, const char *tname, const luaL_Reg *f)
{
    // Verify that this type name has a matching Type ID and type name mapping.
    love::Type ltype;
    if (!love::getType(tname, ltype))
        printf("Missing type entry for type name: %s\n", tname);

    // Get the place for storing and re-using instantiated love types.
    luax_getregistry(L, REGISTRY_TYPES);

    // Create registry._lovetypes if it doesn't exist yet.
    if (!lua_istable(L, -1))
    {
        lua_newtable(L);
        lua_replace(L, -2);

        // Create a metatable.
        lua_newtable(L);

        // metatable.__mode = "v". Weak userdata values.
        lua_pushliteral(L, "v");
        lua_setfield(L, -2, "__mode");

        // setmetatable(newtable, metatable)
        lua_setmetatable(L, -2);

        // registry._lovetypes = newtable
        lua_setfield(L, LUA_REGISTRYINDEX, "_lovetypes");
    }
    else
        lua_pop(L, 1);

    luaL_newmetatable(L, tname);

    // m.__index = m
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");

    // setup gc
    lua_pushcfunction(L, w__gc);
    lua_setfield(L, -2, "__gc");

    // Add equality
    lua_pushcfunction(L, w__eq);
    lua_setfield(L, -2, "__eq");

    // Add tostring function.
    lua_pushstring(L, tname);
    lua_pushcclosure(L, w__tostring, 1);
    lua_setfield(L, -2, "__tostring");

    // Add tostring to as type() as well.
    lua_pushstring(L, tname);
    lua_pushcclosure(L, w__tostring, 1);
    lua_setfield(L, -2, "type");

    // Add typeOf
    lua_pushcfunction(L, w__typeOf);
    lua_setfield(L, -2, "typeOf");

    if (f != 0)
        luax_setfuncs(L, f);

    lua_pop(L, 1); // Pops metatable.
    return 0;
}
Ejemplo n.º 17
0
/***
Install a signal handler for this signal number.
Although this is the same API as signal(2), it uses sigaction for guaranteed semantics.
@function signal
@see signal.lua
@int signum
@tparam[opt=SIG_DFL] function handler function, or `SIG_IGN` or `SIG_DFL` constants
@param[opt] flags the `sa_flags` element of `struct sigaction`
@treturn function previous handler function
@see sigaction(2)
*/
static int
Psignal (lua_State *L)
{
	struct sigaction sa, oldsa;
	int sig = checkint(L, 1), ret;
	void (*handler)(int) = sig_postpone;

	checknargs(L, 3);

	/* Check handler is OK */
	switch (lua_type(L, 2))
	{
		case LUA_TNIL:
		case LUA_TSTRING:
			handler = Fsigmacros[luaL_checkoption(L, 2, "SIG_DFL", Ssigmacros)];
			break;
		case LUA_TFUNCTION:
			if (lua_tocfunction(L, 2) == sig_handler_wrap)
			{
				lua_getupvalue(L, 2, 1);
				handler = lua_touserdata(L, -1);
				lua_pop(L, 1);
			}
			break;
		default:
			argtypeerror(L, 2, "function, string or nil");
			break;
	}

	/* Set up C signal handler, getting old handler */
	sa.sa_handler = handler;
	sa.sa_flags = optint(L, 3, 0);
	sigfillset(&sa.sa_mask);
	ret = sigaction(sig, &sa, &oldsa);
	if (ret == -1)
		return 0;

	/* Set Lua handler if necessary */
	if (handler == sig_postpone)
	{
		lua_pushlightuserdata(L, &signalL); /* We could use an upvalue, but we need this for sig_handle anyway. */
		lua_rawget(L, LUA_REGISTRYINDEX);
		lua_pushvalue(L, 1);
		lua_pushvalue(L, 2);
		lua_rawset(L, -3);
		lua_pop(L, 1);
	}

	/* Push old handler as result */
	if (oldsa.sa_handler == sig_postpone)
	{
		lua_pushlightuserdata(L, &signalL);
		lua_rawget(L, LUA_REGISTRYINDEX);
		lua_pushvalue(L, 1);
		lua_rawget(L, -2);
	} else if (oldsa.sa_handler == SIG_DFL)
		lua_pushstring(L, "SIG_DFL");
	else if (oldsa.sa_handler == SIG_IGN)
		lua_pushstring(L, "SIG_IGN");
	else
	{
		lua_pushinteger(L, sig);
		lua_pushlightuserdata(L, oldsa.sa_handler);
		lua_pushcclosure(L, sig_handler_wrap, 2);
	}
	return 1;
}
Ejemplo n.º 18
0
		void set_function_in_table(lua_State* l, char const* func_name,lua_CFunction func,int tableIndex)
		{
			lua_pushstring(l, func_name);
			lua_pushcclosure(l, func, 0);
			lua_settable(l, tableIndex);
		}
Ejemplo n.º 19
0
static int program_compile(lua_State *L)
{
	shader_type *p = (shader_type*)lua_touserdata(L, 1);

	glLinkProgramARB(p->shader);
	CHECKGLSLLINK(p->shader);

	CHECKGLSLVALID(p->shader);

	char buffer[256];
	int count;
	int dummysize;
	int length;
	GLenum dummytype;

	// New metatable -- stack index 2
	lua_newtable(L);

	// Add GC method
	lua_pushstring(L, "__gc");
	lua_pushcfunction(L, program_free);
	lua_rawset(L, -3);
	
	// New Index -- stack index 4
	lua_pushstring(L, "__index");
	lua_newtable(L);

	// Grab current index table -- stack index 5
	lua_getmetatable(L, 1);
	lua_pushstring(L, "__index");
	lua_rawget(L, -2);
	lua_remove(L, -2);

	// Iterate old index table and copy to new table
	lua_pushnil(L);
	while (lua_next(L, 5) != 0) {
		lua_pushvalue(L, -2);
		lua_pushvalue(L, -2);
		lua_rawset(L, 4);
		lua_pop(L, 1);
	}

	// Pop the old index
	lua_pop(L, 1);

	glGetObjectParameterivARB(p->shader, GL_ACTIVE_UNIFORMS, &count);
	int i;
	for(i = 0; i<count;++i)
	{
		GLint uniLoc;
		glGetActiveUniformARB(p->shader, i, 256, &length, &dummysize, &dummytype, buffer);
		uniLoc = glGetUniformLocationARB(p->shader, buffer);
		if(uniLoc>=0)	// Test for valid uniform location
		{
			printf("*p %i: Uniform: %i: %X %s\n", p->shader,uniLoc, dummytype, buffer);
			// Add a C closure to define the uniform
			if (dummytype == GL_FLOAT) {
				// Compute the name
				lua_pushstring(L, "uni");
				buffer[0] = toupper(buffer[0]);
				lua_pushstring(L, buffer);
				lua_concat(L, 2);
				// Push a closure with the uniform location
				lua_pushnumber(L, uniLoc);
				lua_pushcclosure(L, program_set_uniform_number_fast, 1);
				// Set it in the index table
				lua_rawset(L, 4);
			} else if (dummytype == GL_FLOAT_VEC2) {
				// Compute the name
				lua_pushstring(L, "uni");
				buffer[0] = toupper(buffer[0]);
				lua_pushstring(L, buffer);
				lua_concat(L, 2);
				// Push a closure with the uniform location
				lua_pushnumber(L, uniLoc);
				lua_pushcclosure(L, program_set_uniform_number2_fast, 1);
				// Set it in the index table
				lua_rawset(L, 4);
			} else if (dummytype == GL_FLOAT_VEC3) {
				// Compute the name
				lua_pushstring(L, "uni");
				buffer[0] = toupper(buffer[0]);
				lua_pushstring(L, buffer);
				lua_concat(L, 2);
				// Push a closure with the uniform location
				lua_pushnumber(L, uniLoc);
				lua_pushcclosure(L, program_set_uniform_number3_fast, 1);
				// Set it in the index table
				lua_rawset(L, 4);
			} else if (dummytype == GL_FLOAT_VEC4) {
				// Compute the name
				lua_pushstring(L, "uni");
				buffer[0] = toupper(buffer[0]);
				lua_pushstring(L, buffer);
				lua_concat(L, 2);
				// Push a closure with the uniform location
				lua_pushnumber(L, uniLoc);
				lua_pushcclosure(L, program_set_uniform_number4_fast, 1);
				// Set it in the index table
				lua_rawset(L, 4);
			} else if (dummytype == GL_SAMPLER_2D) {
				// Compute the name
				lua_pushstring(L, "uni");
				buffer[0] = toupper(buffer[0]);
				lua_pushstring(L, buffer);
				lua_concat(L, 2);
				// Push a closure with the uniform location
				lua_pushnumber(L, uniLoc);
				lua_pushcclosure(L, program_set_uniform_texture_fast, 1);
				// Set it in the index table
				lua_rawset(L, 4);
			}
		}
	}

	// Set the index in the metatable
	lua_rawset(L, 2);

	// Set it up (the metatable)
	lua_setmetatable(L, 1);

	p->p_tick = glGetUniformLocationARB(p->shader, "tick");
	p->p_color = glGetUniformLocationARB(p->shader, "displayColor");
	p->p_mapcoord = glGetUniformLocationARB(p->shader, "mapCoord");
	p->p_texsize = glGetUniformLocationARB(p->shader, "texSize");
	p->p_texcoord = glGetUniformLocationARB(p->shader, "texCoord");

	lua_pushboolean(L, TRUE);
	return 1;
}
Ejemplo n.º 20
0
    LUABIND_API void open(lua_State* L)
    {
        bool is_main_thread = lua_pushthread(L) == 1;
        lua_pop(L, 1);

        if (!is_main_thread)
        {
            throw std::runtime_error(
                "luabind::open() must be called with the main thread "
                "lua_State*"
            );
        }

        if (detail::class_registry::get_registry(L))
            return;

        lua_pushstring(L, "__luabind_classes");
        detail::class_registry* r = static_cast<detail::class_registry*>(
            lua_newuserdata(L, sizeof(detail::class_registry)));

        // set gc metatable
        lua_newtable(L);
        lua_pushstring(L, "__gc");
        lua_pushcclosure(
            L
          , detail::garbage_collector_s<
                detail::class_registry
            >::apply
          , 0);

        lua_settable(L, -3);
        lua_setmetatable(L, -2);

        new(r) detail::class_registry(L);
        lua_settable(L, LUA_REGISTRYINDEX);

        lua_pushstring(L, "__luabind_class_id_map");
        void* classes_storage = lua_newuserdata(L, sizeof(detail::class_id_map));
        detail::class_id_map* class_ids = new (classes_storage) detail::class_id_map;
        (void)class_ids;

        lua_newtable(L);
        lua_pushcclosure(L, &destroy_class_id_map, 0);
        lua_setfield(L, -2, "__gc");
        lua_setmetatable(L, -2);

        lua_settable(L, LUA_REGISTRYINDEX);

        lua_pushstring(L, "__luabind_cast_graph");
        void* cast_graph_storage = lua_newuserdata(
            L, sizeof(detail::cast_graph));
        detail::cast_graph* graph = new (cast_graph_storage) detail::cast_graph;
        (void)graph;

        lua_newtable(L);
        lua_pushcclosure(L, &destroy_cast_graph, 0);
        lua_setfield(L, -2, "__gc");
        lua_setmetatable(L, -2);

        lua_settable(L, LUA_REGISTRYINDEX);

        lua_pushstring(L, "__luabind_class_map");
        void* class_map_storage = lua_newuserdata(
            L, sizeof(detail::class_map));
        detail::class_map* classes = new (class_map_storage) detail::class_map;
        (void)classes;

        lua_newtable(L);
        lua_pushcclosure(L, &destroy_class_map, 0);
        lua_setfield(L, -2, "__gc");
        lua_setmetatable(L, -2);

        lua_settable(L, LUA_REGISTRYINDEX);

        // add functions (class, cast etc...)
        lua_pushstring(L, "class");
        lua_pushcclosure(L, detail::create_class::stage1, 0);
        lua_settable(L, LUA_GLOBALSINDEX);

        lua_pushstring(L, "property");
        lua_pushcclosure(L, &make_property, 0);
        lua_settable(L, LUA_GLOBALSINDEX);

        lua_pushlightuserdata(L, &main_thread_tag);
        lua_pushlightuserdata(L, L);
        lua_rawset(L, LUA_REGISTRYINDEX);

        lua_pushstring(L, "super");
        lua_pushcclosure(L, &deprecated_super, 0);
        lua_settable(L, LUA_GLOBALSINDEX);
    }
Ejemplo n.º 21
0
int
luaopen_lem_sqlite3_core(lua_State *L)
{
	/* create module table */
	lua_createtable(L, 0, 11);

	/* create Statement metatable */
	lua_createtable(L, 0, 10);
	lua_pushvalue(L, -1);
	lua_setfield(L, -2, "__index");
	/* insert __gc method */
	lua_pushcfunction(L, stmt_finalize);
	lua_setfield(L, -2, "__gc");
	/* insert finalize method */
	lua_pushcfunction(L, stmt_finalize);
	lua_setfield(L, -2, "finalize");
	/* insert bind method */
	lua_pushcfunction(L, stmt_bind);
	lua_setfield(L, -2, "bind");
	/* insert column_names method */
	lua_pushcfunction(L, stmt_column_names);
	lua_setfield(L, -2, "column_names");
	/* insert step method */
	lua_pushcfunction(L, stmt_step);
	lua_setfield(L, -2, "step");
	/* insert reset method */
	lua_pushcfunction(L, stmt_reset);
	lua_setfield(L, -2, "reset");
	/* insert Statement metatable */
	lua_setfield(L, -2, "Statement");

	/* create Connection metatable */
	lua_createtable(L, 0, 10);
	lua_pushvalue(L, -1);
	lua_setfield(L, -2, "__index");
	/* insert __gc method */
	lua_pushcfunction(L, db_close);
	lua_setfield(L, -2, "__gc");
	/* insert close method */
	lua_pushcfunction(L, db_close);
	lua_setfield(L, -2, "close");
	/* insert last_insert_rowid method */
	lua_pushcfunction(L, db_last_insert_rowid);
	lua_setfield(L, -2, "last_insert_rowid");
	/* insert changes method */
	lua_pushcfunction(L, db_changes);
	lua_setfield(L, -2, "changes");
	/* insert autocommit method */
	lua_pushcfunction(L, db_autocommit);
	lua_setfield(L, -2, "autocommit");
	/* insert prepare method */
	lua_getfield(L, -2, "Statement"); /* upvalue 1: Statement metatable */
	lua_pushcclosure(L, db_prepare, 1);
	lua_setfield(L, -2, "prepare");
	/* insert exec method */
	lua_pushcfunction(L, db_exec);
	lua_setfield(L, -2, "exec");

	/* insert open function */
	lua_pushvalue(L, -1); /* upvalue 1: Connection metatable */
	lua_pushcclosure(L, db_open, 1);
	lua_setfield(L, -3, "open");

	/* insert Connection metatable */
	lua_setfield(L, -2, "Connection");

#if SQLITE_VERSION_NUMBER >= 3005000
	set_open_constant(L, NOMUTEX);
	set_open_constant(L, FULLMUTEX);
	set_open_constant(L, SHAREDCACHE);
	set_open_constant(L, PRIVATECACHE);
	set_open_constant(L, URI);

	set_open_constant(L, READONLY);
	set_open_constant(L, READWRITE);
	set_open_constant(L, CREATE);
#endif

	lua_createtable(L, 0, 0);

#define set_bind_kind(L, name) \
	lua_pushinteger(L, BIND_##name);\
	lua_setfield(L, -2, #name)

	set_bind_kind(L, NUMBER);
	set_bind_kind(L, TEXT);
	set_bind_kind(L, NULL);
	set_bind_kind(L, INT);
	set_bind_kind(L, INT64);
	set_bind_kind(L, BLOB);
	set_bind_kind(L, BLOB64);
	set_bind_kind(L, ZEROBLOB);
	set_bind_kind(L, ZEROBLOB64);

	lua_setfield(L, -2, "bindkind");

	return 1;
}
Ejemplo n.º 22
0
void clua_pushcallback(lua_State* L)
{
	lua_pushcclosure(L,callback_c,1);
}
Ejemplo n.º 23
0
static int luaB_cowrap (lua_State *L) {
  luaB_cocreate(L);
  lua_pushcclosure(L, luaB_auxwrap, 1);
  return 1;
}
Ejemplo n.º 24
0
/**
 * Creates a new coroutine, with body f. f must be a Lua function. 
 * Returns a function that resumes the coroutine each time it is 
 * called. Any arguments passed to the function behave as the extra 
 * arguments to resume. Returns the same values returned by resume, 
 * except the first boolean. In case of error, propagates the error.
 */
static int luaB_cowrap (lua_State *L) {
  luaB_cocreate(L);
  /* 上面函数执行后 function 在栈顶, function 为其 upvalue */
  lua_pushcclosure(L, luaB_auxwrap, 1);
  return 1;
}
Ejemplo n.º 25
0
static void
lua_push_method(lua_State* state, const char* name, size_t length, lua_CFunction fn) {
	lua_pushlstring(state, name, length);
	lua_pushcclosure(state, fn, 0);
	lua_settable(state, -3);
}
Ejemplo n.º 26
0
/* Create the closure necessary to iterate over the array *a with the above function */
static int magnet_array_pairs(lua_State *L, array *a) {
	lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
	lua_pushlightuserdata(L, a); /* Push our array *a into upval 2 */
	lua_pushcclosure(L, magnet_array_next, 2); /* Push our new closure with 2 upvals */
	return 1;
}
Ejemplo n.º 27
0
void thread_particle_init(particle_thread *pt, plist *l)
{
	lua_State *L = pt->L;
	particles_type *ps = l->ps;
	int tile_w, tile_h;
	int base_size = 0;

	// Load the particle definition
	// Returns: generator_fct:1, update_fct:2, max:3, gl:4, no_stop:5
	if (!luaL_loadfile(L, ps->name_def))
	{
		// Make a new table to serve as environment for the function
		lua_newtable(L);
		if (!luaL_loadstring(L, ps->args))
		{
			lua_pushvalue(L, -2); // Copy the evn table
			lua_setfenv(L, -2); // Set it as the function env
			if (lua_pcall(L, 0, 0, 0))
			{
				printf("Particle args init error %x (%s): %s\n", (int)l, ps->args, lua_tostring(L, -1));
				lua_pop(L, 1);
			}
		}
		else
		{
			lua_pop(L, 1);
			printf("Loading particle arguments failed: %s\n", ps->args);
		}

		// Copy tile_w and tile_h for compatibility with old code
		lua_pushstring(L, "engine");
		lua_newtable(L);

		lua_pushstring(L, "Map");
		lua_newtable(L);

		lua_pushstring(L, "tile_w");
		lua_pushstring(L, "tile_w");
		lua_gettable(L, -7);
		tile_w = lua_tonumber(L, -1);
		lua_settable(L, -3);
		lua_pushstring(L, "tile_h");
		lua_pushstring(L, "tile_h");
		lua_gettable(L, -7);
		tile_h = lua_tonumber(L, -1);
		lua_settable(L, -3);

		lua_settable(L, -3);
		lua_settable(L, -3);

		// The metatable which references the global space
		lua_newtable(L);
		lua_pushstring(L, "__index");
		lua_pushvalue(L, LUA_GLOBALSINDEX);
		lua_settable(L, -3);

		// Set the environment metatable
		lua_setmetatable(L, -2);

		// Set the environment
		lua_pushvalue(L, -1);
		lua_setfenv(L, -3);
		lua_insert(L, -2);

		// Call the method
		if (lua_pcall(L, 0, 5, 0))
		{
			printf("Particle run error %x (%s): %s\n", (int)l, ps->args, lua_tostring(L, -1));
			lua_pop(L, 1);
		}

		// Check base size
		lua_pushstring(L, "base_size");
		lua_gettable(L, -7);
		base_size = lua_tonumber(L, -1);
		lua_pop(L, 1);
		lua_remove(L, -6);
	}
	else { lua_pop(L, 1); return; }

	int nb = lua_isnumber(L, 3) ? lua_tonumber(L, 3) : 1000;
	nb = (nb * ps->density) / 100;
	if (!nb) nb = 1;
	ps->nb = nb;
	ps->no_stop = lua_toboolean(L, 5);

	ps->zoom = 1;
	if (base_size)
	{
		ps->zoom = (((float)tile_w + (float)tile_h) / 2) / (float)base_size;
	}

	int batch = nb;
	ps->batch_nb = 0;
	ps->vertices = calloc(2*4*batch, sizeof(GLfloat)); // 2 coords, 4 vertices per particles
	ps->colors = calloc(4*4*batch, sizeof(GLfloat)); // 4 color data, 4 vertices per particles
	ps->texcoords = calloc(2*4*batch, sizeof(GLshort));
	ps->particles = calloc(nb, sizeof(particle_type));

	// Locate the updator
	lua_getglobal(L, "__fcts");
	l->updator_ref = lua_objlen(L, -1) + 1;
	lua_pushnumber(L, lua_objlen(L, -1) + 1);
	lua_pushvalue(L, 2);
	lua_rawset(L, -3);
	lua_pop(L, 1);

	// Grab all parameters
	lua_pushvalue(L, 1);

	lua_pushstring(L, "system_rotation");
	lua_gettable(L, -2);
	ps->rotate = lua_tonumber(L, -1); lua_pop(L, 1);

	lua_pushstring(L, "system_rotationv");
	lua_gettable(L, -2);
	ps->rotate_v = lua_tonumber(L, -1); lua_pop(L, 1);

	lua_pushstring(L, "engine");
	lua_gettable(L, -2);
	ps->engine = lua_tonumber(L, -1); lua_pop(L, 1);

	lua_pushstring(L, "blend_mode");
	lua_gettable(L, -2);
	ps->blend_mode = lua_tonumber(L, -1); lua_pop(L, 1);

	lua_pushstring(L, "generator");
	lua_gettable(L, -2);
	if (lua_isnil(L, -1))
	{
		lua_pop(L, 1);
		l->generator_ref = LUA_NOREF;
	}
	else
	{
		lua_getglobal(L, "__fcts");
		l->generator_ref = lua_objlen(L, -1) + 1;
		lua_pushnumber(L, lua_objlen(L, -1) + 1);
		lua_pushvalue(L, -3);
		lua_rawset(L, -3);
		lua_pop(L, 2);
	}

	if (l->generator_ref == LUA_NOREF)
	{
		lua_pushstring(L, "base");
		lua_gettable(L, -2);
		ps->base = (float)lua_tonumber(L, -1);
		lua_pop(L, 1);

		getinitfield(L, "life", &(ps->life_min), &(ps->life_max));

		getinitfield(L, "angle", &(ps->angle_min), &(ps->angle_max));
		getinitfield(L, "anglev", &(ps->anglev_min), &(ps->anglev_max));
		getinitfield(L, "anglea", &(ps->anglea_min), &(ps->anglea_max));

		getinitfield(L, "size", &(ps->size_min), &(ps->size_max));
		getinitfield(L, "sizev", &(ps->sizev_min), &(ps->sizev_max));
		getinitfield(L, "sizea", &(ps->sizea_min), &(ps->sizea_max));

		getinitfield(L, "r", &(ps->r_min), &(ps->r_max));
		getinitfield(L, "rv", &(ps->rv_min), &(ps->rv_max));
		getinitfield(L, "ra", &(ps->ra_min), &(ps->ra_max));

		getinitfield(L, "g", &(ps->g_min), &(ps->g_max));
		getinitfield(L, "gv", &(ps->gv_min), &(ps->gv_max));
		getinitfield(L, "ga", &(ps->ga_min), &(ps->ga_max));

		getinitfield(L, "b", &(ps->b_min), &(ps->b_max));
		getinitfield(L, "bv", &(ps->bv_min), &(ps->bv_max));
		getinitfield(L, "ba", &(ps->ba_min), &(ps->ba_max));

		getinitfield(L, "a", &(ps->a_min), &(ps->a_max));
		getinitfield(L, "av", &(ps->av_min), &(ps->av_max));
		getinitfield(L, "aa", &(ps->aa_min), &(ps->aa_max));
//		printf("Particle emiter using default generator\n");
	}
	else
	{
//		printf("Particle emiter using custom generator\n");
	}
	lua_pop(L, 1);

	// Pop all returns
	lua_pop(L, 5);

	// Push a special emitter
	lua_newtable(L);
	lua_pushstring(L, "ps");
	lua_newtable(L);

	lua_pushstring(L, "emit");
	lua_pushlightuserdata(L, l);
	lua_pushcclosure(L, particles_emit, 1);
	lua_settable(L, -3);

	lua_settable(L, -3);

	lua_getglobal(L, "__fcts");
	l->emit_ref = lua_objlen(L, -1) + 1;
	lua_pushnumber(L, lua_objlen(L, -1) + 1);
	lua_pushvalue(L, -3);
	lua_rawset(L, -3);
	lua_pop(L, 1);
	lua_pop(L, 1);

	free((char*)ps->name_def);
	free((char*)ps->args);
	ps->name_def = ps->args = NULL;
	ps->init = TRUE;
}
Ejemplo n.º 28
0
static int magnet_env_pairs(lua_State *L) {
	lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
	lua_pushcclosure(L, magnet_env_next, 1); /* Push our new closure with 1 upvals */
	return 1;
}
Ejemplo n.º 29
0
	int w_poll(lua_State * L)
	{
		lua_pushcclosure(L, &poll_i, 0);
		return 1;
	}
Ejemplo n.º 30
0
void dt_lua_gtk_wrap_internal(lua_State*L,const char* function, int line)
{
  lua_pushstring(L,function);
  lua_pushinteger(L,line);
  lua_pushcclosure(L,gtk_wrap,3);
}