示例#1
0
文件: chisel.cpp 项目: SpiderX/sysdig
//
// 1. Iterates through the chisel files on disk (.sc and .lua)
// 2. Opens them and extracts the fields (name, description, etc)
// 3. Adds them to the chisel_descs vector.
//
void sinsp_chisel::get_chisel_list(vector<chisel_desc>* chisel_descs)
{
	uint32_t j;

	for(j = 0; j < g_chisel_dirs->size(); j++)
	{
		if(string(g_chisel_dirs->at(j).m_dir) == "")
		{
			continue;
		}

		tinydir_dir dir;
		tinydir_open(&dir, g_chisel_dirs->at(j).m_dir);

		while(dir.has_next)
		{
			tinydir_file file;
			tinydir_readfile(&dir, &file);

			string fname(file.name);
			string fpath(file.path);

			if(fname.find(".sc") == fname.size() - 3)
			{
				try
				{
					sinsp_chisel ch(NULL, fpath);

					chisel_desc cd;
					cd.m_name = fname.substr(0, fname.rfind('.'));
					cd.m_description = ch.m_description;

					const Json::Value args = (*ch.m_root)["info"]["arguments"];
					for(uint32_t k = 0; k < args.size(); k++)
					{
						cd.m_args.push_back(chiselarg_desc(
			  				args[k]["name"].asString(), 
							args[k]["type"].asString(), 
							args[k]["description"].asString()
						));
					}

					chisel_descs->push_back(cd);
				}
				catch(...)
				{
					//
					// If there was an error opening the chisel, skip to the next one
					//
					goto next_file;
				}
			}

#ifdef HAS_LUA_CHISELS
			if(fname.find(".lua") == fname.size() - 4)
			{
				chisel_desc cd;
				cd.m_name = fname.substr(0, fname.rfind('.'));

				lua_State* ls = lua_open();
 
				luaL_openlibs(ls);
 
				//
				// Load our own lua libs
				//
				luaL_openlib(ls, "sysdig", ll_sysdig, 0);
				luaL_openlib(ls, "chisel", ll_chisel, 0);
				luaL_openlib(ls, "evt", ll_evt, 0);

				//
				// Add our chisel paths to package.path
				//
				for(uint32_t k  = 0; k < g_chisel_dirs->size(); k++)
				{
					string path(g_chisel_dirs->at(k).m_dir);
					path += "?.lua";
					add_lua_package_path(ls, path.c_str());
				}

				//
				// Load the script
				//
				if(luaL_loadfile(ls, fpath.c_str()) || lua_pcall(ls, 0, 0, 0)) 
				{
					goto next_lua_file;
				}

				//
				// Extract the description
				//
				lua_getglobal(ls, "description");
				if(!lua_isstring(ls, -1)) 
				{
					goto next_lua_file;
				}				

				cd.m_description = lua_tostring(ls, -1);

				//
				// Extract the short description
				//
				lua_getglobal(ls, "short_description");
				if(!lua_isstring(ls, -1)) 
				{
					goto next_lua_file;
				}				
				cd.m_shortdesc = lua_tostring(ls, -1);

				// 
				// Extract the category
				//
			  	cd.m_category = "";
				lua_getglobal(ls, "category");
				if(lua_isstring(ls, -1)) 
				{
				  cd.m_category = lua_tostring(ls, -1);
				}				

				//
				// Extract the hidden flag and skip the chisel if it's set
				//
				lua_getglobal(ls, "hidden");
				if(lua_isboolean(ls, -1)) 
				{
					int sares = lua_toboolean(ls, -1);

					if(sares)
					{
						goto next_lua_file;
					}
				}				

				//
				// Extract the args
				//
				lua_getglobal(ls, "args");

				try
				{
					parse_lua_chisel_args(ls, &cd);
				}
				catch(...)
				{
					goto next_lua_file;
				}

				chisel_descs->push_back(cd);
next_lua_file:
				lua_close(ls);
			}
#endif

next_file:
			tinydir_next(&dir);
		}

		tinydir_close(&dir);
	}
}
示例#2
0
void LuaMaterial::Parse(
	lua_State* L,
	const int tableIdx,
	std::function<void(lua_State*, int, LuaMatShader&)> ParseShader,
	std::function<void(lua_State*, int, LuaMatTexture&)> ParseTexture,
	std::function<GLuint(lua_State*, int)> ParseDisplayList
) {
	for (lua_pushnil(L); lua_next(L, tableIdx) != 0; lua_pop(L, 1)) {
		if (!lua_israwstring(L, -2))
			continue;

		const std::string key = StringToLower(lua_tostring(L, -2));

		// uniforms
		if (key.find("uniforms") != std::string::npos) {
			if (!lua_istable(L, -1))
				continue;

			if (key.find("standard") != std::string::npos) {
				uniforms[LuaMatShader::LUASHADER_PASS_FWD].Parse(L, lua_gettop(L));
				continue;
			}
			if (key.find("deferred") != std::string::npos) {
				uniforms[LuaMatShader::LUASHADER_PASS_DFR].Parse(L, lua_gettop(L));
				continue;
			}

			// fallback
			uniforms[LuaMatShader::LUASHADER_PASS_FWD].Parse(L, lua_gettop(L));
			continue;
		}

		// shaders
		if (key.find("shader") != std::string::npos) {
			if (key.find("standard") != std::string::npos) {
				ParseShader(L, -1, shaders[LuaMatShader::LUASHADER_PASS_FWD]);
				continue;
			}
			if (key.find("deferred") != std::string::npos) {
				ParseShader(L, -1, shaders[LuaMatShader::LUASHADER_PASS_DFR]);
				continue;
			}

			// fallback
			ParseShader(L, -1, shaders[LuaMatShader::LUASHADER_PASS_FWD]);
			continue;
		}

		// textures
		if (key.substr(0, 7) == "texunit") {
			if (key.size() < 8)
				continue;

			if (key[7] == 's') {
				// "texunits" = {[0] = string|table, ...}
				if (!lua_istable(L, -1))
					continue;

				const int texTable = lua_gettop(L);

				for (lua_pushnil(L); lua_next(L, texTable) != 0; lua_pop(L, 1)) {
					if (!lua_israwnumber(L, -2))
						continue;

					const unsigned int texUnit = lua_toint(L, -2);

					if (texUnit >= LuaMatTexture::maxTexUnits)
						continue;

					ParseTexture(L, -1, textures[texUnit]);
				}
			} else {
				// "texunitX" = string|table
				const unsigned int texUnit = atoi(key.c_str() + 7);

				if (texUnit >= LuaMatTexture::maxTexUnits)
					continue;

				ParseTexture(L, -1, textures[texUnit]);
			}

			continue;
		}

		// dlists
		if (key == "prelist") {
			preList = ParseDisplayList(L, -1);
			continue;
		}
		if (key == "postlist") {
			postList = ParseDisplayList(L, -1);
			continue;
		}

		// misc
		if (key == "order") {
			order = luaL_checkint(L, -1);
			continue;
		}
		if (key == "culling") {
			if (lua_isnumber(L, -1))
				cullingMode = (GLenum)lua_tonumber(L, -1);

			continue;
		}

		if (key == "usecamera") {
			useCamera = lua_isboolean(L, -1) && lua_toboolean(L, -1);
			continue;
		}

		LOG_L(L_WARNING, "LuaMaterial: incorrect key \"%s\"", key.c_str());
	}
}
示例#3
0
文件: chisel.cpp 项目: SpiderX/sysdig
void sinsp_chisel::set_args(vector<string>* argvals)
{
	uint32_t j, k;

	m_argvals = *argvals;

	if(!m_ls)
	{
		const Json::Value args = (*m_root)["info"]["arguments"];

		//
		// Validate the arguments
		//
		if(m_argvals.size() != args.size())
		{
			throw sinsp_exception("wrong number of parameters for chisel " + m_filename);
		}

		//
		// Apply the arguments
		//
		const Json::Value clst = (*m_root)["chisels"];
		
		for(j = 0; j < clst.size(); j++)
		{
			string filter = clst[j]["filter"].asString();
			for(k = 0; k < args.size(); k++)
			{
				replace_in_place(filter, 
					string("$") + args[k]["name"].asString(), 
					string(m_argvals[k]));
			}

			string formatter = clst[j]["format"].asString();
			for(k = 0; k < args.size(); k++)
			{
				replace_in_place(formatter, 
					string("$") + args[k]["name"].asString(), 
					string(m_argvals[k]));
			}

			chiselinfo* ci = new chiselinfo(m_inspector);
			ci->init(filter, formatter);
			m_subchisels.push_back(ci);
		}
	}
	else
	{
#ifdef HAS_LUA_CHISELS
		//
		// Validate the arguments
		//
		if(m_argvals.size() != m_lua_script_info.m_args.size())
		{
			throw sinsp_exception("wrong number of parameters for chisel " + m_filename);
		}


		//
		// Push the arguments
		//
		for(k = 0; k < m_lua_script_info.m_args.size(); k++)
		{
			lua_getglobal(m_ls, "on_set_arg");
			if(!lua_isfunction(m_ls, -1))
			{
				lua_pop(m_ls, 1);
				throw sinsp_exception("chisel " + m_filename + " misses a set_arg() function.");
			}

			lua_pushstring(m_ls, m_lua_script_info.m_args[k].m_name.c_str()); 
			lua_pushstring(m_ls, m_argvals[k].c_str());

			//
			// call get_info()
			//
			if(lua_pcall(m_ls, 2, 1, 0) != 0) 
			{
				throw sinsp_exception(m_filename + " chisel error: " + lua_tostring(m_ls, -1));
			}

			if(!lua_isboolean(m_ls, -1)) 
			{
				throw sinsp_exception(m_filename + " chisel error: wrong set_arg() return value.");
			}

			int sares = lua_toboolean(m_ls, -1);

			if(!sares)
			{
				throw sinsp_exception("set_arg() for chisel " + m_filename + " failed.");
			}

			lua_pop(m_ls, 1);
		}
#endif
	}
}
示例#4
0
int lua_multimin_minimize(lua_State * L) {
    bool ssdel=false;
    double eps=0.00001;
    double tol=0.0001;
    double step_size=0.01;
    int maxiter=1000;
    bool print=false;
    array<double> * x=0;
    array<double> * ss=0;
    const gsl_multimin_fminimizer_type *Tf = 0;
    const gsl_multimin_fdfminimizer_type *Tdf = 0;


    multi_param mp;
    mp.L=L;
    mp.fdf_index=-1;

    lua_pushstring(L,"f");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.f_index=luaL_ref(L, LUA_REGISTRYINDEX);
    } else {
        luaL_error(L,"%s\n","missing function");
    }

    lua_pushstring(L,"df");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.df_index=luaL_ref(L, LUA_REGISTRYINDEX);
        Tdf= gsl_multimin_fdfminimizer_conjugate_fr;
    } else {
        lua_pop(L,1);
        Tf= gsl_multimin_fminimizer_nmsimplex2;
    }

    lua_pushstring(L,"fdf");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.fdf_index=luaL_ref(L, LUA_REGISTRYINDEX);
    } else {
        lua_pop(L,1);
        mp.fdf_index=-1;
    }

    lua_pushstring(L,"algorithm");
    lua_gettable(L,-2);
    if(lua_isstring(L,-1)) {
        if(Tf!=0) {
            if(!strcmp(lua_tostring(L,-1),"nmsimplex")) {
                Tf = gsl_multimin_fminimizer_nmsimplex;
            } else if(!strcmp(lua_tostring(L,-1),"nmsimplex2rand")) {
                Tf = gsl_multimin_fminimizer_nmsimplex2rand;
            } else if(!strcmp(lua_tostring(L,-1),"nmsimplex2")) {
                Tf = gsl_multimin_fminimizer_nmsimplex2;
            } else {
                luaL_error(L,"%s\n","invalid algorithm");
            }
        } else {
            if(!strcmp(lua_tostring(L,-1),"conjugate_pr")) {
                Tdf = gsl_multimin_fdfminimizer_conjugate_pr;
            } else if(!strcmp(lua_tostring(L,-1),"steepest_descent")) {
                Tdf = gsl_multimin_fdfminimizer_steepest_descent;
            } else if(!strcmp(lua_tostring(L,-1),"vector_bfgs")) {
                Tdf = gsl_multimin_fdfminimizer_vector_bfgs;
            } else if(!strcmp(lua_tostring(L,-1),"vector_bfgs2")) {
                Tdf = gsl_multimin_fdfminimizer_vector_bfgs2;
            } else if(!strcmp(lua_tostring(L,-1),"conjugate_fr")) {
                Tdf = gsl_multimin_fdfminimizer_conjugate_fr;
            } else {
                luaL_error(L,"%s\n","invalid algorithm");
            }
        }
    }
    lua_pop(L,1);

    lua_pushstring(L,"show_iterations");
    lua_gettable(L,-2);
    if(lua_isboolean(L,-1)) {
        print=(lua_toboolean(L,-1)==1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"eps");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        eps=lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"step_size");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        step_size=lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"tol");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        tol=lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"maxiter");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        maxiter=(int)lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"starting_point");
    lua_gettable(L,-2);
    if(!lua_isuserdata(L,-1)) lua_error(L);
    if (!SWIG_IsOK(SWIG_ConvertPtr(L,-1,(void**)&x,SWIGTYPE_p_arrayT_double_t,0))){
        luaL_error(L,"%s\n","missing starting point");
    }
    lua_pop(L,1);

    if(Tf) {
        lua_pushstring(L,"step_sizes");
        lua_gettable(L,-2);
        if(lua_isuserdata(L,-1)) {
            if (!SWIG_IsOK(SWIG_ConvertPtr(L,-1,(void**)&ss,SWIGTYPE_p_arrayT_double_t,0))){
                lua_error(L);
            }
        } else {
            ssdel=true;
            ss=new array<double>(x->size());
            ss->set_all(1.0);
            if(lua_isnumber(L,-1)) {
                double v=lua_tonumber(L,-1);
                ss->set_all(v);
            }
        }
        lua_pop(L,1);
    }

    lua_pop(L,1);

    if(Tf) {
        gsl_multimin_fminimizer *s = NULL;
        gsl_vector SS, X;
        gsl_multimin_function minex_func;

        int iter = 0;
        int status;
        double size;
        int N=x->size();

        /* Starting point */
        X.size=x->size();
        X.stride=1;
        X.data=x->data();
        X.owner=0;

        /* Set initial step sizes */
        SS.size=ss->size();
        SS.stride=1;
        SS.data=ss->data();
        SS.owner=0;

        /* Initialize method and iterate */
        minex_func.n = N;
        minex_func.f = multimin_f_cb;
        minex_func.params = &mp;

        s = gsl_multimin_fminimizer_alloc (Tf, N);
        gsl_multimin_fminimizer_set (s, &minex_func, &X, &SS);
        if(print)  printf ("running algorithm '%s'\n",
                gsl_multimin_fminimizer_name (s));
        do
        {
            iter++;
            status = gsl_multimin_fminimizer_iterate(s);

            if (status)
                break;

            size = gsl_multimin_fminimizer_size (s);
            status = gsl_multimin_test_size (size, eps);

            if (status == GSL_SUCCESS)
            {
                if(print) printf ("converged to minimum at\n");
            }

            if(print) printf ("%5d f() = %12.3f size = %.9f\n",
                    iter,
                    s->fval, size);
        } while (status == GSL_CONTINUE && iter < maxiter);
        for(int i=0;i<N;++i) x->set(i,gsl_vector_get(s->x,i));
        luaL_unref(L, LUA_REGISTRYINDEX, mp.f_index);
        gsl_multimin_fminimizer_free (s);
    } else {
        gsl_multimin_fdfminimizer *s = NULL;
        gsl_vector X;
        gsl_multimin_function_fdf minex_func;

        int iter = 0;
        int status;
        double size;
        int N=x->size();

        /* Starting point */
        X.size=x->size();
        X.stride=1;
        X.data=x->data();
        X.owner=0;

        /* Initialize method and iterate */
        minex_func.n = N;
        minex_func.f = multimin_f_cb;
        minex_func.df = multimin_df_cb;
        minex_func.fdf = multimin_fdf_cb;
        minex_func.params = &mp;

        s = gsl_multimin_fdfminimizer_alloc (Tdf, N);
        gsl_multimin_fdfminimizer_set (s, &minex_func, &X, step_size, tol);
        if(print)  printf ("running algorithm '%s'\n",
                gsl_multimin_fdfminimizer_name (s));
        do
        {
            iter++;
            status = gsl_multimin_fdfminimizer_iterate(s);

            if (status)
                break;

            status = gsl_multimin_test_gradient (s->gradient, eps);

            if (status == GSL_SUCCESS)
            {
                if(print) printf ("converged to minimum at\n");
            }

            if(print) printf ("%5d f() = %12.3f\n",
                    iter,
                    s->f);
        } while (status == GSL_CONTINUE && iter < maxiter);
        for(int i=0;i<N;++i) x->set(i,gsl_vector_get(s->x,i));
        luaL_unref(L, LUA_REGISTRYINDEX, mp.f_index);
        luaL_unref(L, LUA_REGISTRYINDEX, mp.df_index);
        gsl_multimin_fdfminimizer_free (s);
    }
    if(mp.fdf_index>=0) {
        luaL_unref(L, LUA_REGISTRYINDEX, mp.fdf_index);
    }
    if(ssdel) {
        delete ss;
    }
    return 0;
}
示例#5
0
// bool
static bool luapuz_checkboolean(lua_State * L, int index)
{
    if (! lua_isboolean(L, index))
        luaL_typerror(L, index, "boolean");
    return (bool)lua_toboolean(L, index);
}
示例#6
0
void read_object_properties(lua_State *L, int index,
		ObjectProperties *prop)
{
	if(index < 0)
		index = lua_gettop(L) + 1 + index;
	if(!lua_istable(L, index))
		return;

	prop->hp_max = getintfield_default(L, -1, "hp_max", 10);

	getboolfield(L, -1, "physical", prop->physical);
	getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);

	getfloatfield(L, -1, "weight", prop->weight);

	lua_getfield(L, -1, "collisionbox");
	if(lua_istable(L, -1))
		prop->collisionbox = read_aabb3f(L, -1, 1.0);
	lua_pop(L, 1);

	getstringfield(L, -1, "visual", prop->visual);

	getstringfield(L, -1, "mesh", prop->mesh);

	lua_getfield(L, -1, "visual_size");
	if(lua_istable(L, -1))
		prop->visual_size = read_v2f(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "textures");
	if(lua_istable(L, -1)){
		prop->textures.clear();
		int table = lua_gettop(L);
		lua_pushnil(L);
		while(lua_next(L, table) != 0){
			// key at index -2 and value at index -1
			if(lua_isstring(L, -1))
				prop->textures.push_back(lua_tostring(L, -1));
			else
				prop->textures.push_back("");
			// removes value, keeps key for next iteration
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "colors");
	if(lua_istable(L, -1)){
		prop->colors.clear();
		int table = lua_gettop(L);
		lua_pushnil(L);
		while(lua_next(L, table) != 0){
			// key at index -2 and value at index -1
			if(lua_isstring(L, -1))
				prop->colors.push_back(readARGB8(L, -1));
			else
				prop->colors.push_back(video::SColor(255, 255, 255, 255));
			// removes value, keeps key for next iteration
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "spritediv");
	if(lua_istable(L, -1))
		prop->spritediv = read_v2s16(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "initial_sprite_basepos");
	if(lua_istable(L, -1))
		prop->initial_sprite_basepos = read_v2s16(L, -1);
	lua_pop(L, 1);

	getboolfield(L, -1, "is_visible", prop->is_visible);
	getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
	getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
	getfloatfield(L, -1, "stepheight", prop->stepheight);
	prop->stepheight*=BS;
	lua_getfield(L, -1, "automatic_face_movement_dir");
	if (lua_isnumber(L, -1)) {
		prop->automatic_face_movement_dir = true;
		prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
	} else if (lua_isboolean(L, -1)) {
		prop->automatic_face_movement_dir = lua_toboolean(L, -1);
		prop->automatic_face_movement_dir_offset = 0.0;
	}
	lua_pop(L, 1);
}
示例#7
0
int lua_multiroot_solve(lua_State * L) {
    double eps=0.00001;
    int maxiter=1000;
    bool print=false;
    array<double> * x=0;
    const gsl_multiroot_fsolver_type *Tf = 0;
    const gsl_multiroot_fdfsolver_type *Tdf = 0;

    multi_param mp;
    mp.L=L;
    mp.fdf_index=-1;

    lua_pushstring(L,"f");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.f_index=luaL_ref(L, LUA_REGISTRYINDEX);
    } else {
        luaL_error(L,"%s\n","missing function");
    }

    lua_pushstring(L,"df");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.df_index=luaL_ref(L, LUA_REGISTRYINDEX);
        Tdf= gsl_multiroot_fdfsolver_hybridsj;
    } else {
        lua_pop(L,1);
        Tf=  gsl_multiroot_fsolver_hybrids;
    }

    lua_pushstring(L,"fdf");
    lua_gettable(L,-2);
    if(lua_isfunction(L,-1)) {
        mp.fdf_index=luaL_ref(L, LUA_REGISTRYINDEX);
    } else {
        lua_pop(L,1);
        mp.fdf_index=-1;
    }

    lua_pushstring(L,"algorithm");
    lua_gettable(L,-2);
    if(lua_isstring(L,-1)) {
        if(Tf) {
            if(!strcmp(lua_tostring(L,-1),"hybrid")) {
                Tf = gsl_multiroot_fsolver_hybrid;
            } else if(!strcmp(lua_tostring(L,-1),"dnewton")) {
                Tf = gsl_multiroot_fsolver_dnewton;
            } else if(!strcmp(lua_tostring(L,-1),"hybrids")) {
                Tf = gsl_multiroot_fsolver_hybrids;
            } else if(!strcmp(lua_tostring(L,-1),"broyden")) {
                Tf = gsl_multiroot_fsolver_broyden;
            } else {
                luaL_error(L,"%s\n","invalid algorithm");
            }
        } else {
            if(!strcmp(lua_tostring(L,-1),"hybridj")) {
                Tdf = gsl_multiroot_fdfsolver_hybridj;
            } else if(!strcmp(lua_tostring(L,-1),"newton")) {
                Tdf = gsl_multiroot_fdfsolver_newton;
            } else if(!strcmp(lua_tostring(L,-1),"hybridsj")) {
                Tdf = gsl_multiroot_fdfsolver_hybridsj;
            } else if(!strcmp(lua_tostring(L,-1),"gnewton")) {
                Tdf = gsl_multiroot_fdfsolver_gnewton;
            } else {
                luaL_error(L,"%s\n","invalid algorithm");
            }
        }
    }
    lua_pop(L,1);

    lua_pushstring(L,"show_iterations");
    lua_gettable(L,-2);
    if(lua_isboolean(L,-1)) {
        print=(lua_toboolean(L,-1)==1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"eps");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        eps=lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"maxiter");
    lua_gettable(L,-2);
    if(lua_isnumber(L,-1)) {
        maxiter=(int)lua_tonumber(L,-1);
    }
    lua_pop(L,1);

    lua_pushstring(L,"starting_point");
    lua_gettable(L,-2);
    if(!lua_isuserdata(L,-1)) lua_error(L);
    if (!SWIG_IsOK(SWIG_ConvertPtr(L,-1,(void**)&x,SWIGTYPE_p_arrayT_double_t,0))){
        lua_error(L);
    }
    lua_pop(L,1);

    lua_pop(L,1);
    if(Tf) {
        gsl_multiroot_fsolver *s = NULL;
        gsl_vector X;
        gsl_multiroot_function sol_func;

        int iter = 0;
        int status;
        double size;
        int N=x->size();

        /* Starting point */
        X.size=x->size();
        X.stride=1;
        X.data=x->data();
        X.owner=0;

        /* Initialize method and iterate */
        sol_func.n = N;
        sol_func.f = multiroot_f_cb;
        sol_func.params = &mp;

        s = gsl_multiroot_fsolver_alloc (Tf, N);
        gsl_multiroot_fsolver_set (s, &sol_func, &X);
        if(print)  printf ("running algorithm '%s'\n",
                gsl_multiroot_fsolver_name (s));
        do
        {
            iter++;
            status = gsl_multiroot_fsolver_iterate(s);

            if (status)
                break;

            status = gsl_multiroot_test_residual (s->f, eps);

            if(print) {
                printf ("%5d f() = ", iter);
                gsl_vector_fprintf(stdout,  s->f, "%f");
            }
        } while (status == GSL_CONTINUE && iter < maxiter);
        for(int i=0;i<N;++i) x->set(i,gsl_vector_get(s->x,i));
        luaL_unref(L, LUA_REGISTRYINDEX, mp.f_index);
        gsl_multiroot_fsolver_free (s);
    } else {
        gsl_multiroot_fdfsolver *s = NULL;
        gsl_vector X;
        gsl_multiroot_function_fdf sol_func;

        int iter = 0;
        int status;
        double size;
        int N=x->size();

        /* Starting point */
        X.size=x->size();
        X.stride=1;
        X.data=x->data();
        X.owner=0;

        /* Initialize method and iterate */
        sol_func.n = N;
        sol_func.f = multiroot_f_cb;
        sol_func.df = multiroot_df_cb;
        sol_func.fdf = multiroot_fdf_cb;
        sol_func.params = &mp;

        s = gsl_multiroot_fdfsolver_alloc (Tdf, N);
        gsl_multiroot_fdfsolver_set (s, &sol_func, &X);
        if(print)  printf ("running algorithm '%s'\n",
                gsl_multiroot_fdfsolver_name (s));
        do
        {
            iter++;
            status = gsl_multiroot_fdfsolver_iterate(s);

            if (status)
                break;

            status = gsl_multiroot_test_residual (s->f, eps);

            if(print) {
                printf ("%5d f() = ", iter);
                gsl_vector_fprintf(stdout,  s->f, "%f");
            }
        } while (status == GSL_CONTINUE && iter < maxiter);
        for(int i=0;i<N;++i) x->set(i,gsl_vector_get(s->x,i));
        luaL_unref(L, LUA_REGISTRYINDEX, mp.f_index);
        luaL_unref(L, LUA_REGISTRYINDEX, mp.df_index);
        gsl_multiroot_fdfsolver_free (s);
    }
    if(mp.fdf_index>=0) luaL_unref(L, LUA_REGISTRYINDEX, mp.fdf_index);
    return 0;
}
示例#8
0
LUALIB_API int luaL_checkboolean (lua_State *L, int narg) {
  int d = lua_toboolean(L, narg);
  if (d == 0 && !lua_isboolean(L, narg))  /* avoid extra test when d is not 0 */
    tag_error(L, narg, LUA_TBOOLEAN);
  return d;
}
示例#9
0
bool Script::syncFrom(SafeArray<LuaType>* lt){

	#ifndef OLD_SYNC
		return true;
	#endif

	if(!doSync){
		return true;
	}

	if(lt==NULL){
		lt=&global;
	}

	for(int i=0; i<lt->size(); i++){
		if((*lt)[i].type==SCRIPT_TABLE_INT){
			lua_pushnumber(L, (*lt)[i].nameint);
			
		}else{
			lua_pushstring(L, (*lt)[i].name.cStr());
		}

		if(lt==&global){
			lua_gettable(L, LUA_GLOBALSINDEX); //get table[key] 
		}else{
			lua_gettable(L, -2);
		}

		if((*lt)[i].type==SCRIPT_TABLE){
			if(lua_istable(L, -1)){
				syncFrom(&(*lt)[i].children);
			}else{
				if(!(*lt)[i].newTable){
					console().write("type mismatch: '"+(*lt)[i].name+"' needs to a table");
				}
				//lua_pop(L, 1);	//IMPORTANT TO NOT HAVE THIS
			}
		}else if((*lt)[i].type==SCRIPT_TABLE_INT){
			if(lua_istable(L, -1)){
				syncFrom(&(*lt)[i].children);
			}else{
				if(!(*lt)[i].newTable){
				console().write("type mismatch: '"+String((*lt)[i].nameint)+"' needs to a table");
				}
				//lua_pop(L, 1);	//IMPORTANT TO NOT HAVE THIS
			}
		}else if((*lt)[i].type==SCRIPT_INT){
			if(lua_isnumber(L, -1)){
				double t=lua_tonumber(L, -1);
				lua_pop(L, 1);

				if(lt==&global){
					*(*lt)[i].value.i=(int)t;
				}else{
					*(*lt)[i].value.i=(int)t;
				}

			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a number");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else if((*lt)[i].type==SCRIPT_INT_STORED){
			if(lua_isnumber(L, -1)){
				double t=lua_tonumber(L, -1);
				lua_pop(L, 1);
			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a number");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else if((*lt)[i].type==SCRIPT_FLOAT){
			if(lua_isnumber(L, -1)){
				double t=lua_tonumber(L, -1);
				lua_pop(L, 1);

				if(lt==&global){
					*(*lt)[i].value.f=(float)t;
				}else{
					*(*lt)[i].value.f=(float)t;
				}

			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a number");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else if((*lt)[i].type==SCRIPT_DOUBLE){
			if(lua_isnumber(L, -1)){

				double t=lua_tonumber(L, -1);
				lua_pop(L, 1);

				if(lt==&global){
					*(*lt)[i].value.d=t;
				}else{
					*(*lt)[i].value.d=t;
				}

			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a number");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else if((*lt)[i].type==SCRIPT_BOOL){
			if(lua_isboolean(L, -1)){
				bool t=lua_toboolean(L, -1);
				lua_pop(L, 1);

				if(lt==&global){
					*(*lt)[i].value.b=t;
				}else{
					*(*lt)[i].value.b=t;
				}

			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a boolean");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else if((*lt)[i].type==SCRIPT_STRING){
			if(lua_isstring(L, -1)){
				String t=lua_tostring(L, -1);
				lua_pop(L, 1);

				if(lt==&global){
					*(*lt)[i].value.s=t;
				}else{
					*(*lt)[i].value.s=t;
				}

			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a string");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}

		}else if((*lt)[i].type==SCRIPT_FUNCTION){
			if(lua_isfunction(L, -1)){
				lua_pop(L, 1);
			}else{
				console().write("type mismatch: '"+(*lt)[i].name+"' needs to a function");
				lua_pop(L, 1);	//IMPORTANT - NEED TO HAVE
			}
		}else{
			console().write("SYNCFROM: type mismatch: '"+(*lt)[i].name+"' bad type");
		}


	}

	lua_pop(L, 1);
	
	return true;
}
示例#10
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);
        
//        /* create object ptr -> class type mapping table */
//        lua_pushstring(L, "tolua_ptr2type");
//        lua_newtable(L);
//        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,"isnull",tolua_bnd_isnulluserdata);
        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);
}
示例#11
0
static int lua_co_tcp(lua_State *L)
{
    cosocket_t *c*k = (cosocket_t *) lua_newuserdata(L, sizeof(cosocket_t));

    if(!c*k) {
        lua_pushnil(L);
        lua_pushstring(L, "stack error!");
        return 2;
    }

    bzero(c*k, sizeof(cosocket_t));

    if(lua_isstring(L, 1) && lua_isstring(L, 2)) {
        if(c*k->ctx) {
            SSL_CTX_free(c*k->ctx);
        }

        c*k->ctx = SSL_CTX_new(SSLv23_client_method());

        if(c*k->ctx == NULL) {
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_new Error");
            return 2;
        }

        if(lua_isstring(L, 3)) {
            if(c*k->ssl_pw) {
                free(c*k->ssl_pw);
            }

            size_t len = 0;
            const char *p1 = lua_tolstring(L, 3, &len);
            c*k->ssl_pw = malloc(len + 1);

            if(c*k->ssl_pw) {
                memcpy(c*k->ssl_pw, p1, len);
                c*k->ssl_pw[len] = '\0';
                SSL_CTX_set_default_passwd_cb_userdata(c*k->ctx, (void *)c*k->ssl_pw);
                SSL_CTX_set_default_passwd_cb(c*k->ctx, ssl_password_cb);
            }

            int l = snprintf(temp_buf, 4096, "%s:%s:%s", lua_tostring(L, 1), lua_tostring(L, 2), p1);
            c*k->ssl_sign = fnv1a_32(temp_buf, l);

        } else {
            int l = snprintf(temp_buf, 4096, "%s:%s:", lua_tostring(L, 1), lua_tostring(L, 2));
            c*k->ssl_sign = fnv1a_32(temp_buf, l);
        }

        if(SSL_CTX_use_certificate_file(c*k->ctx, lua_tostring(L, 1), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_use_certificate_file Error");
            return 2;
        }

        if(SSL_CTX_use_PrivateKey_file(c*k->ctx, lua_tostring(L, 2), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_use_PrivateKey_file Error");
            return 2;
        }

        if(!SSL_CTX_check_private_key(c*k->ctx)) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_check_private_key Error");
            return 2;
        }

        c*k->use_ssl = 1;

    } else if(lua_isboolean(L, 1) && lua_toboolean(L, 1) == 1) {
        c*k->use_ssl = 1;

    } else {
        c*k->use_ssl = 0;
    }

    c*k->L = L;
    c*k->fd = -1;
    c*k->timeout = 30000;
    /*
    if(luaL_newmetatable(L, "cosocket")) {
        //luaL_checkstack(L, 1, "not enough stack to register connection MT");
        lua_pushvalue(L, lua_upvalueindex(1));
        setfuncs(L, M, 1);
        lua_pushvalue(L, -1);
        lua_setfield(L, -2, "__index");
    }*/
    luaL_getmetatable(L, "cosocket:tcp");
    lua_setmetatable(L, -2);

    return 1;
}
示例#12
0
static void var_dump( lua_State* L, int depth ) 
{
    // All the different datatypes need to be handled differently
    if ( lua_isnil( L, -1 ) ) 
    {
        print_padded_line( depth, "NIL" );
    }
    else if ( lua_isfunction( L, -1 ) ) 
    {
        print_padded_line( depth, "FUNCTION" );
    }
    else if ( lua_isuserdata( L, -1 ) ) 
    {
        print_padded_line( depth, "USERDATA" );
    }
    else if ( lua_isthread( L, -1 ) ) 
    {
        print_padded_line( depth, "THREAD" );
    }
    else if ( lua_isboolean( L, -1 ) ) 
    {        
        print_padded_line( depth, "boolean(%s)", lua_toboolean( L, -1 ) == true ? "true" : "false" );
    }
    else if ( lua_isnumber( L, -1 ) )
    {
        double number = lua_tonumber( L, -1 );

        if ( (double)(int)number == number ) 
        {
            print_padded_line( depth, "integer(%i)", (int)number );
        }
        else
        {
            print_padded_line( depth, "float(%f)", number );
        }
    }
    else if( lua_isstring( L, -1 ) ) 
    {
        print_padded_line( depth, "string(%d) \"%s\"", lua_strlen( L, -1 ), lua_tostring( L, -1 ) );
    }
    else if( lua_istable( L, -1 ) ) 
    {
        print_padded_line( depth, "table(%i) {", lua_objlen( L, -1 ) );

        // Push nil as first key before calling next
        lua_pushnil( L );
        while ( lua_next(L, -2 ) != 0 ) {            
            if ( lua_isnumber( L, -2 ) ) 
            {
                print_padded_line( depth + 1, "[%i] =>", lua_tointeger( L, -2 ) );
            }
            else
            {
                print_padded_line( depth + 1, "[\"%s\"] =>", lua_tostring( L, -2 ) );                
            }
            var_dump( L, depth + 1 );
        }
        print_padded_line( depth, "}" );
    }

    lua_pop( L, 1 );
}
示例#13
0
void BoolFromLua(lua_State *L, int index, Variable *ref)
{
    assert(lua_isboolean(L, index));
    int temp = lua_toboolean(L, index);
    ref->SetData(ref->Meta()->NewCopy(&temp));
}
示例#14
0
文件: imlua_image.c 项目: LuaDist/im
/*****************************************************************************\
 image:GetAttribute(attrib)
\*****************************************************************************/
static int imluaImageGetAttribute (lua_State *L)
{
  int data_type;
  int i, count;
  const void *data;
  int as_string = 0;

  imImage* image = imlua_checkimage(L, 1);
  const char *attrib = luaL_checkstring(L, 2);

  data = imImageGetAttribute(image, attrib, &data_type, &count);
  if (!data)
  {
    lua_pushnil(L);
    return 1;
  }

  if (data_type == IM_BYTE && lua_isboolean(L, 3))
    as_string = lua_toboolean(L, 3);

  if (!as_string)
    lua_newtable(L);
  
  switch (data_type)
  {
  case IM_BYTE:
    {
      if (as_string)
      {
        lua_pushstring(L, (const char*)data);
      }
      else
      {
        imbyte *data_byte = (imbyte*) data;
        for (i = 0; i < count; i++, data_byte++)
        {
          lua_pushnumber(L, *data_byte);
          lua_rawseti(L, -2, i+1);
        }
      }
    }
    break;

  case IM_SHORT:
    {
      short *data_short = (short*) data;
      for (i = 0; i < count; i++, data_short += 2)
      {
        lua_pushnumber(L, *data_short);
        lua_rawseti(L, -2, i+1);
      }
    }
    break;

  case IM_USHORT:
    {
      imushort *data_ushort = (imushort*) data;
      for (i = 0; i < count; i++, data_ushort += 2)
      {
        lua_pushnumber(L, *data_ushort);
        lua_rawseti(L, -2, i+1);
      }
    }
    break;

  case IM_INT:
    {
      int *data_int = (int*) data;
      for (i = 0; i < count; i++, data_int++)
      {
        lua_pushnumber(L, *data_int);
        lua_rawseti(L, -2, i+1);
      }
    }
    break;

  case IM_FLOAT:
    {
      float *data_float = (float*) data;
      for (i = 0; i < count; i++, data_float++)
      {
        lua_pushnumber(L, *data_float);
        lua_rawseti(L, -2, i+1);
      }
    }
    break;

  case IM_CFLOAT:
    {
      float *data_float = (float*) data;
      for (i = 0; i < count; i++, data_float += 2)
      {
        imlua_newarrayfloat(L, data_float, 2, 1);
        lua_rawseti(L, -2, i+1);
      }        
    }
    break;
  }

  lua_pushnumber(L, data_type);

  return 2;
}
示例#15
0
文件: stack.cpp 项目: bacek/xscript
void
luaCheckBoolean(lua_State *lua, int index) {
    if (!lua_isboolean(lua, index)) {
        throw BadType("boolean", index);
    }
}
示例#16
0
void EventHandler::resumeThread(lua_State *state) {
    Glib::Threads::Mutex::Lock lock(m_Mutex);

    while ((!eventQueue.empty() || timeout < 0.05) && stopHandler == false) {
        int args = 0;
        if (!eventQueue.empty()) {
            eevent ev = eventQueue.front();
            args = ev.size();
            for (int i = 0; i < ev.size(); i++) // Could use an iterator here
            {
                eventParameter par = ev[i];
                if (par.type == 0) // number
                {
                    lua_pushnumber(state, par.number);
                }
                else if (par.type == 1) // boolean
                {
                    lua_pushboolean(state, par.boolean);
                }
                else if (par.type == 2) // string
                {
                    lua_pushstring(state, par.string.c_str());
                }
                else {
                    lua_pushnil(state);
                }
            }
            eventQueue.pop();
        }

        resume:
        // std::cout << "Resuming " << lua_status(state) << ", " << args << std::endl;
        int suc = lua_resume(state, NULL, args);
        if (suc == LUA_YIELD) {
            if (lua_isfunction(state, 1)) {
                // std::cout << "Running function" << std::endl;
                lua_pushvalue(state, 1); // I guess I'm supposed to run the function?
                lua_pcall(state, 0, LUA_MULTRET, 0);

                args = lua_gettop(state);
                goto resume;
            }
            else if (lua_isboolean(state, 1)) {
                // Shutdown
            }
            else if (lua_isnumber(state, 1)) {
                timeout = lua_tonumber(state, 1);
            }
        }
        else if (suc == LUA_OK) {
            if (lua_isboolean(state, 1) && lua_toboolean(state, 1) == 0) {
                std::cerr << "Error: " << lua_tostring(state, 2) << std::endl;
            }
            stopHandler = true;
        }
        else if (suc == LUA_ERRRUN) {
            std::cerr << "Runtime error: " << lua_tostring(state, -1) << std::endl;
            stopHandler = true;
        }
    }
}