コード例 #1
0
ファイル: serialize.c プロジェクト: fangjianh/skynet-vs2013
static int
lua_isinteger(lua_State *L, int index) {
	int32_t x = (int32_t)lua_tointeger(L,index);
	lua_Number n = lua_tonumber(L,index);
	return ((lua_Number)x==n);
}
コード例 #2
0
void call_va(lua_State *L, const char *func, const char *sig, ...) {
	va_list vl;
	int narg, nres; /* number of arguments and results */
	va_start(vl, sig);
	lua_getglobal(L, func); /* get function */
	/* push arguments */
	narg = 0;
	while (*sig) { /* push arguments */
		switch (*sig++) {
			case 'd': /* double argument */
				lua_pushnumber(L, va_arg(vl, double));
				break;
			case 'i': /* int argument */
				lua_pushnumber(L, va_arg(vl, int));
				break;
			case 's': /* string argument */
				lua_pushstring(L, va_arg(vl, char *));
				break;
			case '>':
				goto endwhile;
				break;
			default:
				error(L, "invalid option (%c)", *(sig - 1));
		}
		narg++;
		luaL_checkstack(L, 1, "too many arguments");
	} 
endwhile:
	/* do the call */
	nres = strlen(sig); /* number of expected results */
	if (lua_pcall(L, narg, nres, 0) != 0) /* do the call */
		error(L, "error running function '%s': %s",
		func, lua_tostring(L, -1));
	/* retrieve results */
	nres = -nres; /* stack index of first result */
	while (*sig) { /* get results */
		switch (*sig++) {
			case 'd': /* double result */
			{
				if (!lua_isnumber(L, nres))
					error(L, "wrong result type");
				*va_arg(vl, double *) = lua_tonumber(L, nres);
			}
			break;
			case 'i': /* int result */
			{
				if (!lua_isnumber(L, nres))
					error(L, "wrong result type");
				*va_arg(vl, int *) = (int)lua_tonumber(L, nres);
			}
			break;
			case 's': /* string result */
			{
				if (!lua_isstring(L, nres))
					error(L, "wrong result type");
				*va_arg(vl, const char **) = lua_tostring(L, nres);
			}
			break;
			default:
				error(L, "invalid option (%c)", *(sig - 1));
		}
		nres++;
	}
	va_end(vl);
}
コード例 #3
0
ファイル: premake.c プロジェクト: Lusito/premake
/**
 * When running in debug mode, the scripts are loaded from the disk. The path to
 * the scripts must be provided via either the /scripts command line option or
 * the PREMAKE_PATH environment variable.
 */
int load_builtin_scripts(lua_State* L)
{
	const char* filename;

	/* call os.pathsearch() to locate _premake_main.lua */
	lua_pushcfunction(L, os_pathsearch);
	lua_pushstring(L, "_premake_main.lua");
	lua_pushstring(L, scripts_path);
	lua_pushstring(L, getenv("PREMAKE_PATH"));
	lua_call(L, 3, 1);

	if (lua_isnil(L, -1))
	{
		printf(ERROR_MESSAGE,
			"Unable to find _premake_main.lua; use /scripts option when in debug mode!\n"
			"Please refer to the documentation (or build in release mode instead)."
		);
		return !OKAY;
	}

	/* load the manifest, which includes all the required scripts */
	scripts_path = lua_tostring(L, -1);
	filename = lua_pushfstring(L, "%s/_manifest.lua", scripts_path);
	if (luaL_dofile(L, filename))
	{
		printf(ERROR_MESSAGE, lua_tostring(L, -1));
		return !OKAY;
	}

	lua_pushnil(L);
	while (lua_next(L, -2))
	{
		filename = lua_pushfstring(L, "%s/%s", scripts_path, lua_tostring(L, -1));
		if (luaL_dofile(L, filename)) {
			printf(ERROR_MESSAGE, lua_tostring(L, -1));
			return !OKAY;
		}
		lua_pop(L, 2);
	}
	lua_pop(L, 1);

	/* run the bootstrapping script */
	filename = lua_pushfstring(L, "%s/_premake_main.lua", scripts_path);
	if (luaL_dofile(L, filename))
	{
		printf(ERROR_MESSAGE, lua_tostring(L, -1));
		return !OKAY;
	}

	/* in debug mode, show full traceback on all errors */
	lua_getglobal(L, "debug");
	lua_getfield(L, -1, "traceback");

	/* hand off control to the scripts */
	lua_getglobal(L, "_premake_main");
	if (lua_pcall(L, 0, 1, -2) != OKAY)
	{
		printf(ERROR_MESSAGE, lua_tostring(L, -1));
		return !OKAY;
	}
	else
	{
		return (int)lua_tonumber(L, -1);
	}
}
コード例 #4
0
ファイル: LuaRules.cpp プロジェクト: azotlikid/spring
/**
 * called after every damage modification (even HitByWeaponId)
 * but before the damage is applied
 *
 * expects two numbers returned by lua code:
 * 1st is stored under *newDamage if newDamage != NULL
 * 2nd is stored under *impulseMult if impulseMult != NULL
 */
bool CLuaRules::UnitPreDamaged(const CUnit* unit, const CUnit* attacker,
                             float damage, int weaponID, bool paralyzer,
                             float* newDamage, float* impulseMult)
{
	if (!haveUnitPreDamaged) {
		return false;
	}

	LUA_CALL_IN_CHECK(L);
	lua_checkstack(L, 11);

	const int errfunc = SetupTraceback(L);
	static const LuaHashString cmdStr("UnitPreDamaged");

	if (!cmdStr.GetGlobalFunc(L)) {
		// remove error handler
		if (errfunc) { lua_pop(L, 1); }
		return false; // the call is not defined
	}

	int argCount = 5;
	lua_pushnumber(L, unit->id);
	lua_pushnumber(L, unit->unitDef->id);
	lua_pushnumber(L, unit->team);
	lua_pushnumber(L, damage);
	lua_pushboolean(L, paralyzer);
	if (GetFullRead(L)) {
		lua_pushnumber(L, weaponID);
		argCount += 1;
		if (attacker != NULL) {
			lua_pushnumber(L, attacker->id);
			lua_pushnumber(L, attacker->unitDef->id);
			lua_pushnumber(L, attacker->team);
			argCount += 3;
		}
	}

	// call the routine
	RunCallInTraceback(cmdStr, argCount, 2, errfunc);

	if (newDamage && lua_isnumber(L, -2)) {
		*newDamage = lua_tonumber(L, -2);
	} else if (!lua_isnumber(L, -2) || lua_isnil(L, -2)) {
		// first value is obligatory, so may not be nil
		LOG_L(L_WARNING,
				"%s(): 1st value returned should be a number (newDamage)",
				cmdStr.GetString().c_str());
	}

	if (impulseMult && lua_isnumber(L, -1)) {
		*impulseMult = lua_tonumber(L, -1);
	} else if (!lua_isnumber(L, -1) && !lua_isnil(L, -1)) {
		// second value is optional, so nils are OK
		LOG_L(L_WARNING,
				"%s(): 2nd value returned should be a number (impulseMult)",
				cmdStr.GetString().c_str());
	}

	lua_pop(L, 2);
	return true;
}
コード例 #5
0
ファイル: wrap_Event.cpp プロジェクト: JackDanger/love
	int _wrap_registerSignal(lua_State *L)
	{
		luaL_argcheck(L, lua_isnumber(L, 1), 1, "Expected number");
		lua_pushboolean(L, instance->registerSignal(lua_tonumber(L, 1)));
		return 1;
	}
コード例 #6
0
ファイル: lauxlib.c プロジェクト: korman/Temp
LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
    lua_Number d = lua_tonumber(L, narg);
    if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
        tag_error(L, narg, LUA_TNUMBER);
    return d;
}
コード例 #7
0
ファイル: options.cpp プロジェクト: cpehle/lean
static int options_get_double(lua_State * L) {
    int nargs = lua_gettop(L);
    double defval = nargs < 3 ? 0.0 : lua_tonumber(L, 3);
    return push_number(L, to_options(L, 1).get_double(to_name_ext(L, 2), defval));
}
コード例 #8
0
static bool luapuz_isuint(lua_State * L, int index, bool strong = false)
{
    if (! luapuz_isnumber(L, index, strong))
        return false;
    return lua_tonumber(L, index) >= 0;
}
コード例 #9
0
ファイル: lnet.cpp プロジェクト: The-Megax/lua
LUA_API double luanet_tonumber (lua_State *L, int idx)
{
	return lua_tonumber (L, idx);
}
コード例 #10
0
ファイル: mysql.c プロジェクト: diroussel/lua-web-tools
/*
 * Executes a MySQL statement.
 */
static int execute (lua_State *L) {
    mysql_rec *m;
    const char *sql;
    unsigned long param_count;
    int i;
    size_t len;

    m = (mysql_rec *) luaL_checkudata(L, 1, IS_MYSQL_METATABLE);
    if (!m->mysql) {
        lua_pushliteral(L, "connection is closed");
        lua_error(L);
    }
    sql = luaL_checkstring(L, 2);

    /* close open statement */
    if (m->res) {
        mysql_free_result(m->res);
        m->res = NULL;
    }
    if (m->stmt) {
        mysql_stmt_close(m->stmt);
        m->stmt = NULL;
    }

    /* prepare */
    m->stmt = mysql_stmt_init(m->mysql);
    if (!m->stmt) {
        error(L, m);
    }
    if (mysql_stmt_prepare(m->stmt, sql, strlen(sql)) != 0) {
        error(L, m);
    }

    /* bind params */
    param_count = mysql_stmt_param_count(m->stmt);
    if (lua_gettop(L) - 2 != param_count) {
        luaL_error(L, "expected %d bind params, got %d", param_count,
                   lua_gettop(L) - 2);
    }
    if (param_count > IS_MYSQL_MAXPARAM) {
        luaL_error(L, "maximum %d bind params, got %d",
                   IS_MYSQL_MAXPARAM, param_count);
    }
    memset(m->bind, 0, param_count * sizeof(MYSQL_BIND));
    for (i = 0; i < param_count; i++) {
        switch (lua_type(L, i + 3)) {
        case LUA_TNIL:
            m->bind[i].buffer_type = MYSQL_TYPE_NULL;
            break;

        case LUA_TBOOLEAN:
            m->bind[i].buffer_type = MYSQL_TYPE_DOUBLE;
            m->doubles[i] = lua_toboolean(L, i + 3)
                            ? 1.0 : 0.0;
            m->bind[i].buffer = &m->doubles[i];
            break;

        case LUA_TNUMBER:
            m->bind[i].buffer_type = MYSQL_TYPE_DOUBLE;
            m->doubles[i] = (double) lua_tonumber(L, i + 3);
            m->bind[i].buffer = &m->doubles[i];
            break;

        case LUA_TSTRING:
            m->bind[i].buffer_type = MYSQL_TYPE_STRING;
            m->bind[i].buffer = (void *) lua_tolstring(L, i + 3,
                                &len);
            m->bind[i].buffer_length = len;
            m->bind[i].length = &m->bind[i].buffer_length;
            break;

        default:
            luaL_error(L, "unsupported %s bind param %d",
                       luaL_typename(L, i + 3), i + 1);
        }
    }
    if (mysql_stmt_bind_param(m->stmt, m->bind) != 0) {
        error(L, m);
    }

    /* execute */
    if (mysql_stmt_execute(m->stmt) != 0) {
        error(L, m);
    }

    /* setup fetch */
    m->res = mysql_stmt_result_metadata(m->stmt);
    if (m->res) {
        m->field_count = mysql_num_fields(m->res);
        if (m->field_count > IS_MYSQL_MAXPARAM) {
            luaL_error(L, "maximum %d bind results, got %d",
                       IS_MYSQL_MAXPARAM, m->field_count);
        }
        m->fields = mysql_fetch_fields(m->res);
        memset(m->bind, 0, m->field_count * sizeof(MYSQL_BIND));
        for (i = 0; i < m->field_count; i++) {
            switch (m->fields[i].type) {
            case MYSQL_TYPE_NULL:
                m->bind[i].buffer_type = MYSQL_TYPE_NULL;
                break;

            case MYSQL_TYPE_TINY:
            case MYSQL_TYPE_SHORT:
            case MYSQL_TYPE_LONG:
            case MYSQL_TYPE_INT24:
            case MYSQL_TYPE_LONGLONG:
            case MYSQL_TYPE_DECIMAL:
            case MYSQL_TYPE_NEWDECIMAL:
            case MYSQL_TYPE_FLOAT:
            case MYSQL_TYPE_DOUBLE:
                m->bind[i].buffer_type = MYSQL_TYPE_DOUBLE;
                m->bind[i].buffer = &m->doubles[i];
                m->bind[i].is_null = &m->nulls[i];
                break;

            case MYSQL_TYPE_BIT:
                m->bind[i].buffer_type = MYSQL_TYPE_BIT;
                m->bind[i].buffer = &m->doubles[i];
                m->bind[i].buffer_length = sizeof(double);
                m->bind[i].length = &m->lengths[i];
                m->bind[i].is_null = &m->nulls[i];
                break;

            case MYSQL_TYPE_TIMESTAMP:
            case MYSQL_TYPE_DATE:
            case MYSQL_TYPE_TIME:
            case MYSQL_TYPE_DATETIME:
            case MYSQL_TYPE_YEAR:
            case MYSQL_TYPE_STRING:
            case MYSQL_TYPE_VAR_STRING:
            case MYSQL_TYPE_BLOB:
            case MYSQL_TYPE_SET:
            case MYSQL_TYPE_ENUM:
            case MYSQL_TYPE_GEOMETRY:
                m->bind[i].buffer_type = MYSQL_TYPE_STRING;
                m->bind[i].length = &m->lengths[i];
                m->bind[i].is_null = &m->nulls[i];
                break;

            default:
                luaL_error(L, "unsupported type %d result "
                           "param %d", m->fields[i].type,
                           i + 1);
            }
        }
        if (mysql_stmt_bind_result(m->stmt, m->bind) != 0) {
            error(L, m);
        }

        /* no result */
        return 0;
    } else {
        /* return number of rows affected */
        lua_pushinteger(L, (lua_Integer) mysql_stmt_affected_rows(
                            m->stmt));
        return 1;
    }
}
コード例 #11
0
ファイル: lua_object.hpp プロジェクト: CliffsDover/wesnoth
inline std::shared_ptr<double> lua_object<double>::to_type(lua_State *L, int n)
{
	return std::shared_ptr<double>(new double(lua_tonumber(L, n)));
}
コード例 #12
0
ファイル: luagsl.cpp プロジェクト: vinicius-mello/local
int lua_integration_integrate(lua_State * L) {
    double a=0.0;
    double b=1.0;
    double c=0.5;
    double epsabs=0.0;
    double epsrel=0.0000001;
    double alpha=0.0;
    double beta=0.0;
    int mu=0;
    int nu=0;
    size_t limit=100;
    size_t n=0;
    int key=1;
    double result=0;
    double abserr=0;
    size_t neval=0;

    gsl_integration_workspace * w=0;

    multi_param mp;
    mp.L=L;

    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");
    }
    gsl_function F;
    F.function = &int_f_cb;
    F.params = &mp;

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

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

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

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

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

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

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

    if(limit>n) n=limit;

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

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

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

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

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

    lua_pushstring(L,"algorithm");
    lua_gettable(L,-2);
    if(lua_isstring(L,-1)) {
        if(!strcmp(lua_tostring(L,-1),"qng")) {
            gsl_integration_qng(&F,a,b,epsabs,epsrel,&result,&abserr,&neval);
        } else if(!strcmp(lua_tostring(L,-1),"qag")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qag(&F,a,b,epsabs,epsrel,limit,key,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qags")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qags(&F,a,b,epsabs,epsrel,limit,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qagi")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qagi(&F,epsabs,epsrel,limit,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qagiu")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qagiu(&F,a,epsabs,epsrel,limit,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qagil")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qagil(&F,b,epsabs,epsrel,limit,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qawc")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qawc(&F,a,b,c,epsabs,epsrel,limit,w,&result,&abserr);
        } else if(!strcmp(lua_tostring(L,-1),"qaws")) {
            w=gsl_integration_workspace_alloc(n);
            gsl_integration_qaws_table * table=gsl_integration_qaws_table_alloc(alpha,beta,mu,nu);
            gsl_integration_qaws(&F,a,b,table,epsabs,epsrel,limit,w,&result,&abserr);
            gsl_integration_qaws_table_free(table);
        } else if(!strcmp(lua_tostring(L,-1),"cquad")) {
            gsl_integration_cquad_workspace * w=gsl_integration_cquad_workspace_alloc(n);
            gsl_integration_cquad(&F,a,b,epsabs,epsrel,w,&result,&abserr,&neval);
            gsl_integration_cquad_workspace_free(w);
        } else {
            luaL_error(L,"%s\n","invalid algorithm");
        }
    } else {
        gsl_integration_cquad_workspace * w=gsl_integration_cquad_workspace_alloc(n);
        gsl_integration_cquad(&F,a,b,epsabs,epsrel,w,&result,&abserr,&neval);
        gsl_integration_cquad_workspace_free(w);
    }
    lua_pop(L,1);

    lua_pop(L,1);

    lua_pushnumber(L,result);
    lua_pushnumber(L,abserr);
    lua_pushnumber(L,neval);
    if(mp.fdf_index>=0) luaL_unref(L, LUA_REGISTRYINDEX, mp.fdf_index);
    if(w) gsl_integration_workspace_free(w);
    return 3;
}
コード例 #13
0
ファイル: luagsl.cpp プロジェクト: vinicius-mello/local
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;
}
コード例 #14
0
ファイル: luagsl.cpp プロジェクト: vinicius-mello/local
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;
}
コード例 #15
0
ファイル: lualib.c プロジェクト: j0t4/espardino
static int delay_us_lua (lua_State *L)
{

	delay_us(lua_tonumber(L,1));
	return 0;
}
コード例 #16
0
static int
ngx_http_lua_ngx_location_capture_multi(lua_State *L)
{
    ngx_http_request_t              *r;
    ngx_http_request_t              *sr = NULL; /* subrequest object */
    ngx_http_post_subrequest_t      *psr;
    ngx_http_lua_ctx_t              *sr_ctx;
    ngx_http_lua_ctx_t              *ctx;
    ngx_array_t                     *extra_vars;
    ngx_str_t                        uri;
    ngx_str_t                        args;
    ngx_str_t                        extra_args;
    ngx_uint_t                       flags;
    u_char                          *p;
    u_char                          *q;
    size_t                           len;
    size_t                           nargs;
    int                              rc;
    int                              n;
    int                              always_forward_body = 0;
    ngx_uint_t                       method;
    ngx_http_request_body_t         *body;
    int                              type;
    ngx_buf_t                       *b;
    unsigned                         vars_action;
    ngx_uint_t                       nsubreqs;
    ngx_uint_t                       index;
    size_t                           sr_statuses_len;
    size_t                           sr_headers_len;
    size_t                           sr_bodies_len;
    size_t                           sr_flags_len;
    unsigned                         custom_ctx;
    ngx_http_lua_co_ctx_t           *coctx;

    ngx_http_lua_post_subrequest_data_t      *psr_data;

    n = lua_gettop(L);
    if (n != 1) {
        return luaL_error(L, "only one argument is expected, but got %d", n);
    }

    luaL_checktype(L, 1, LUA_TTABLE);

    nsubreqs = lua_objlen(L, 1);
    if (nsubreqs == 0) {
        return luaL_error(L, "at least one subrequest should be specified");
    }

    r = ngx_http_lua_get_req(L);
    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
    if (ctx == NULL) {
        return luaL_error(L, "no ctx found");
    }

    ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE
                               | NGX_HTTP_LUA_CONTEXT_ACCESS
                               | NGX_HTTP_LUA_CONTEXT_CONTENT);

    coctx = ctx->cur_co_ctx;
    if (coctx == NULL) {
        return luaL_error(L, "no co ctx found");
    }

    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "lua location capture, uri:\"%V\" c:%ud", &r->uri,
                   r->main->count);

    sr_statuses_len = nsubreqs * sizeof(ngx_int_t);
    sr_headers_len  = nsubreqs * sizeof(ngx_http_headers_out_t *);
    sr_bodies_len   = nsubreqs * sizeof(ngx_str_t);
    sr_flags_len    = nsubreqs * sizeof(uint8_t);

    p = ngx_pcalloc(r->pool, sr_statuses_len + sr_headers_len +
                    sr_bodies_len + sr_flags_len);

    if (p == NULL) {
        return luaL_error(L, "no memory");
    }

    coctx->sr_statuses = (void *) p;
    p += sr_statuses_len;

    coctx->sr_headers = (void *) p;
    p += sr_headers_len;

    coctx->sr_bodies = (void *) p;
    p += sr_bodies_len;

    coctx->sr_flags = (void *) p;

    coctx->nsubreqs = nsubreqs;

    coctx->pending_subreqs = 0;

    extra_vars = NULL;

    for (index = 0; index < nsubreqs; index++) {
        coctx->pending_subreqs++;

        lua_rawgeti(L, 1, index + 1);
        if (lua_isnil(L, -1)) {
            return luaL_error(L, "only array-like tables are allowed");
        }

        dd("queries query: top %d", lua_gettop(L));

        if (lua_type(L, -1) != LUA_TTABLE) {
            return luaL_error(L, "the query argument %d is not a table, "
                              "but a %s",
                              index, lua_typename(L, lua_type(L, -1)));
        }

        nargs = lua_objlen(L, -1);

        if (nargs != 1 && nargs != 2) {
            return luaL_error(L, "query argument %d expecting one or "
                              "two arguments", index);
        }

        lua_rawgeti(L, 2, 1); /* queries query uri */

        dd("queries query uri: %d", lua_gettop(L));

        dd("first arg in first query: %s", lua_typename(L, lua_type(L, -1)));

        body = NULL;

        ngx_str_null(&extra_args);

        if (extra_vars != NULL) {
            /* flush out existing elements in the array */
            extra_vars->nelts = 0;
        }

        vars_action = 0;

        custom_ctx = 0;

        if (nargs == 2) {
            /* check out the options table */

            lua_rawgeti(L, 2, 2); /* queries query uri opts */

            dd("queries query uri opts: %d", lua_gettop(L));

            if (lua_type(L, 4) != LUA_TTABLE) {
                return luaL_error(L, "expecting table as the 2nd argument for "
                                  "subrequest %d, but got %s", index,
                                  luaL_typename(L, 4));
            }

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the args option */

            lua_getfield(L, 4, "args");

            type = lua_type(L, -1);

            switch (type) {
            case LUA_TTABLE:
                ngx_http_lua_process_args_option(r, L, -1, &extra_args);
                break;

            case LUA_TNIL:
                /* do nothing */
                break;

            case LUA_TNUMBER:
            case LUA_TSTRING:
                extra_args.data = (u_char *) lua_tolstring(L, -1, &len);
                extra_args.len = len;

                break;

            default:
                return luaL_error(L, "Bad args option value");
            }

            lua_pop(L, 1);

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the vars option */

            lua_getfield(L, 4, "vars");

            switch (lua_type(L, -1)) {
            case LUA_TTABLE:
                ngx_http_lua_process_vars_option(r, L, -1, &extra_vars);

                dd("post process vars top: %d", lua_gettop(L));
                break;

            case LUA_TNIL:
                /* do nothing */
                break;

            default:
                return luaL_error(L, "Bad vars option value");
            }

            lua_pop(L, 1);

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the share_all_vars option */

            lua_getfield(L, 4, "share_all_vars");

            switch (lua_type(L, -1)) {
            case LUA_TNIL:
                /* do nothing */
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, -1)) {
                    vars_action |= NGX_HTTP_LUA_SHARE_ALL_VARS;
                }
                break;

            default:
                return luaL_error(L, "Bad share_all_vars option value");
            }

            lua_pop(L, 1);

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the copy_all_vars option */

            lua_getfield(L, 4, "copy_all_vars");

            switch (lua_type(L, -1)) {
            case LUA_TNIL:
                /* do nothing */
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, -1)) {
                    vars_action |= NGX_HTTP_LUA_COPY_ALL_VARS;
                }
                break;

            default:
                return luaL_error(L, "Bad copy_all_vars option value");
            }

            lua_pop(L, 1);

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the "forward_body" option */

            lua_getfield(L, 4, "always_forward_body");
            always_forward_body = lua_toboolean(L, -1);
            lua_pop(L, 1);

            dd("always foward body: %d", always_forward_body);

            /* check the "method" option */

            lua_getfield(L, 4, "method");

            type = lua_type(L, -1);

            if (type == LUA_TNIL) {
                method = NGX_HTTP_GET;

            } else {
                if (type != LUA_TNUMBER) {
                    return luaL_error(L, "Bad http request method");
                }

                method = (ngx_uint_t) lua_tonumber(L, -1);
            }

            lua_pop(L, 1);

            dd("queries query uri opts: %d", lua_gettop(L));

            /* check the "ctx" option */

            lua_getfield(L, 4, "ctx");

            type = lua_type(L, -1);

            if (type != LUA_TNIL) {
                if (type != LUA_TTABLE) {
                    return luaL_error(L, "Bad ctx option value type %s, "
                                      "expected a Lua table",
                                      lua_typename(L, type));
                }

                custom_ctx = 1;

            } else {
                lua_pop(L, 1);
            }

            dd("queries query uri opts ctx?: %d", lua_gettop(L));

            /* check the "body" option */

            lua_getfield(L, 4, "body");

            type = lua_type(L, -1);

            if (type != LUA_TNIL) {
                if (type != LUA_TSTRING && type != LUA_TNUMBER) {
                    return luaL_error(L, "Bad http request body");
                }

                body = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t));

                if (body == NULL) {
                    return luaL_error(L, "no memory");
                }

                q = (u_char *) lua_tolstring(L, -1, &len);

                dd("request body: [%.*s]", (int) len, q);

                if (len) {
                    b = ngx_create_temp_buf(r->pool, len);
                    if (b == NULL) {
                        return luaL_error(L, "no memory");
                    }

                    b->last = ngx_copy(b->last, q, len);

                    body->bufs = ngx_alloc_chain_link(r->pool);
                    if (body->bufs == NULL) {
                        return luaL_error(L, "no memory");
                    }

                    body->bufs->buf = b;
                    body->bufs->next = NULL;

                    body->buf = b;
                }
            }

            lua_pop(L, 1); /* pop the body */

            /* stack: queries query uri opts ctx? */

            lua_remove(L, 4);

            /* stack: queries query uri ctx? */

            dd("queries query uri ctx?: %d", lua_gettop(L));

        } else {
            method = NGX_HTTP_GET;
        }

        /* stack: queries query uri ctx? */

        p = (u_char *) luaL_checklstring(L, 3, &len);

        uri.data = ngx_palloc(r->pool, len);
        if (uri.data == NULL) {
            return luaL_error(L, "memory allocation error");
        }

        ngx_memcpy(uri.data, p, len);

        uri.len = len;

        ngx_str_null(&args);

        flags = 0;

        rc = ngx_http_parse_unsafe_uri(r, &uri, &args, &flags);
        if (rc != NGX_OK) {
            dd("rc = %d", (int) rc);

            return luaL_error(L, "unsafe uri in argument #1: %s", p);
        }

        if (args.len == 0) {
            if (extra_args.len) {
                p = ngx_palloc(r->pool, extra_args.len);
                if (p == NULL) {
                    return luaL_error(L, "no memory");
                }

                ngx_memcpy(p, extra_args.data, extra_args.len);

                args.data = p;
                args.len = extra_args.len;
            }

        } else if (extra_args.len) {
            /* concatenate the two parts of args together */
            len = args.len + (sizeof("&") - 1) + extra_args.len;

            p = ngx_palloc(r->pool, len);
            if (p == NULL) {
                return luaL_error(L, "no memory");
            }

            q = ngx_copy(p, args.data, args.len);
            *q++ = '&';
            ngx_memcpy(q, extra_args.data, extra_args.len);

            args.data = p;
            args.len = len;
        }

        p = ngx_pnalloc(r->pool, sizeof(ngx_http_post_subrequest_t)
                        + sizeof(ngx_http_lua_ctx_t)
                        + sizeof(ngx_http_lua_post_subrequest_data_t));
        if (p == NULL) {
            return luaL_error(L, "no memory");
        }

        psr = (ngx_http_post_subrequest_t *) p;

        p += sizeof(ngx_http_post_subrequest_t);

        sr_ctx = (ngx_http_lua_ctx_t *) p;

        p += sizeof(ngx_http_lua_ctx_t);

        psr_data = (ngx_http_lua_post_subrequest_data_t *) p;

        ngx_memzero(sr_ctx, sizeof(ngx_http_lua_ctx_t));

        /* set by ngx_memzero:
         *      sr_ctx->run_post_subrequest = 0
         *      sr_ctx->free = NULL
         *      sr_ctx->body = NULL
         */

        psr_data->ctx = sr_ctx;
        psr_data->pr_co_ctx = coctx;

        psr->handler = ngx_http_lua_post_subrequest;
        psr->data = psr_data;

        rc = ngx_http_lua_subrequest(r, &uri, &args, &sr, psr, 0);

        if (rc != NGX_OK) {
            return luaL_error(L, "failed to issue subrequest: %d", (int) rc);
        }

        ngx_http_lua_init_ctx(sr, sr_ctx);

        sr_ctx->capture = 1;
        sr_ctx->index = index;
        sr_ctx->last_body = &sr_ctx->body;
        sr_ctx->vm_state = ctx->vm_state;

        ngx_http_set_ctx(sr, sr_ctx, ngx_http_lua_module);

        rc = ngx_http_lua_adjust_subrequest(sr, method, always_forward_body,
                                            body, vars_action, extra_vars);

        if (rc != NGX_OK) {
            ngx_http_lua_cancel_subreq(sr);
            return luaL_error(L, "failed to adjust the subrequest: %d",
                              (int) rc);
        }

        dd("queries query uri opts ctx? %d", lua_gettop(L));

        /* stack: queries query uri ctx? */

        if (custom_ctx) {
            ngx_http_lua_ngx_set_ctx_helper(L, sr, sr_ctx, -1);
            lua_pop(L, 3);

        } else {
            lua_pop(L, 2);
        }

        /* stack: queries */
    }

    if (extra_vars) {
        ngx_array_destroy(extra_vars);
    }

    ctx->no_abort = 1;

    return lua_yield(L, 0);
}
コード例 #17
0
ファイル: lmarshal.cpp プロジェクト: ElevimRG/LuaEngine
static void mar_encode_value(lua_State *L, mar_Buffer *buf, int val, size_t *idx)
{
    size_t l;
    int val_type = lua_type(L, val);
    if (lua_isinteger(L, val))
        val_type = MAR_TINT;
    lua_pushvalue(L, val);

    buf_write(L, (const char*)&val_type, MAR_CHR, buf);
    switch (val_type) {
    case LUA_TBOOLEAN: {
        int int_val = lua_toboolean(L, -1);
        buf_write(L, (const char*)&int_val, MAR_CHR, buf);
        break;
    }
    case LUA_TSTRING: {
        const char *str_val = lua_tolstring(L, -1, &l);
        buf_write(L, (const char*)&l, MAR_I32, buf);
        buf_write(L, str_val, l, buf);
        break;
    }
    case LUA_TNUMBER: {
        lua_Number num_val = lua_tonumber(L, -1);
        buf_write(L, (const char*)&num_val, MAR_I64, buf);
        break;
    }
    case MAR_TINT: {
        lua_Integer num_val = lua_tointeger(L, -1);
        buf_write(L, (const char*)&num_val, MAR_I64, buf);
        break;
    }
    case LUA_TTABLE: {
        int tag, ref;
        lua_pushvalue(L, -1);
        lua_rawget(L, SEEN_IDX);
        if (!lua_isnil(L, -1)) {
            ref = lua_tointeger(L, -1);
            tag = MAR_TREF;
            buf_write(L, (const char*)&tag, MAR_CHR, buf);
            buf_write(L, (const char*)&ref, MAR_I32, buf);
            lua_pop(L, 1);
        }
        else {
            mar_Buffer rec_buf;
            lua_pop(L, 1); /* pop nil */
            if (luaL_getmetafield(L, -1, "__persist")) {
                tag = MAR_TUSR;

                lua_pushvalue(L, -2); /* self */
                lua_call(L, 1, 1);
                if (!lua_isfunction(L, -1)) {
                    luaL_error(L, "__persist must return a function");
                }

                lua_remove(L, -2); /* __persist */

                lua_newtable(L);
                lua_pushvalue(L, -2); /* callback */
                lua_rawseti(L, -2, 1);

                buf_init(L, &rec_buf);
                mar_encode_table(L, &rec_buf, idx);

                buf_write(L, (const char*)&tag, MAR_CHR, buf);
                buf_write(L, (const char*)&rec_buf.head, MAR_I32, buf);
                buf_write(L, rec_buf.data, rec_buf.head, buf);
                buf_done(L, &rec_buf);
                lua_pop(L, 1);
            }
            else {
                tag = MAR_TVAL;

                lua_pushvalue(L, -1);
                lua_pushinteger(L, (*idx)++);
                lua_rawset(L, SEEN_IDX);

                lua_pushvalue(L, -1);
                buf_init(L, &rec_buf);
                mar_encode_table(L, &rec_buf, idx);
                lua_pop(L, 1);

                buf_write(L, (const char*)&tag, MAR_CHR, buf);
                buf_write(L, (const char*)&rec_buf.head, MAR_I32, buf);
                buf_write(L, rec_buf.data,rec_buf.head, buf);
                buf_done(L, &rec_buf);
            }
        }
        break;
    }
    case LUA_TFUNCTION: {
        int tag, ref;
        lua_pushvalue(L, -1);
        lua_rawget(L, SEEN_IDX);
        if (!lua_isnil(L, -1)) {
            ref = lua_tointeger(L, -1);
            tag = MAR_TREF;
            buf_write(L, (const char*)&tag, MAR_CHR, buf);
            buf_write(L, (const char*)&ref, MAR_I32, buf);
            lua_pop(L, 1);
        }
        else {
            mar_Buffer rec_buf;
            unsigned int i;
            lua_Debug ar;
            lua_pop(L, 1); /* pop nil */

            lua_pushvalue(L, -1);
            lua_getinfo(L, ">nuS", &ar);
            if (ar.what[0] != 'L') {
                luaL_error(L, "attempt to persist a C function '%s'", ar.name);
            }
            tag = MAR_TVAL;
            lua_pushvalue(L, -1);
            lua_pushinteger(L, (*idx)++);
            lua_rawset(L, SEEN_IDX);

            lua_pushvalue(L, -1);
            buf_init(L, &rec_buf);
            lua_dump(L, (lua_Writer)buf_write, &rec_buf, true);

            buf_write(L, (const char*)&tag, MAR_CHR, buf);
            buf_write(L, (const char*)&rec_buf.head, MAR_I32, buf);
            buf_write(L, rec_buf.data, rec_buf.head, buf);
            buf_done(L, &rec_buf);
            lua_pop(L, 1);

            lua_createtable(L, ar.nups, 0);
            for (i = 1; i <= ar.nups; i++) {
                const char* upvalue_name = lua_getupvalue(L, -2, i);
                if (strcmp("_ENV", upvalue_name) == 0) {
                    lua_pop(L, 1);
                    // Mark where _ENV is expected.
                    lua_pushstring(L, MAR_ENV_IDX_KEY);
                    lua_pushinteger(L, i);
                    lua_rawset(L, -3);
                }
                else {
                    lua_rawseti(L, -2, i);
                }
            }
            lua_pushstring(L, MAR_NUPS_IDX_KEY);
            lua_pushnumber(L, ar.nups);
            lua_rawset(L, -3);

            buf_init(L, &rec_buf);
            mar_encode_table(L, &rec_buf, idx);

            buf_write(L, (const char*)&rec_buf.head, MAR_I32, buf);
            buf_write(L, rec_buf.data, rec_buf.head, buf);
            buf_done(L, &rec_buf);
            lua_pop(L, 1);
        }

        break;
    }
    case LUA_TUSERDATA: {
        int tag, ref;
        lua_pushvalue(L, -1);
        lua_rawget(L, SEEN_IDX);
        if (!lua_isnil(L, -1)) {
            ref = lua_tointeger(L, -1);
            tag = MAR_TREF;
            buf_write(L, (const char*)&tag, MAR_CHR, buf);
            buf_write(L, (const char*)&ref, MAR_I32, buf);
            lua_pop(L, 1);
        }
        else {
            mar_Buffer rec_buf;
            lua_pop(L, 1); /* pop nil */
            if (luaL_getmetafield(L, -1, "__persist")) {
                tag = MAR_TUSR;

                lua_pushvalue(L, -2);
                lua_pushinteger(L, (*idx)++);
                lua_rawset(L, SEEN_IDX);

                lua_pushvalue(L, -2);
                lua_call(L, 1, 1);
                if (!lua_isfunction(L, -1)) {
                    luaL_error(L, "__persist must return a function");
                }
                lua_newtable(L);
                lua_pushvalue(L, -2);
                lua_rawseti(L, -2, 1);
                lua_remove(L, -2);

                buf_init(L, &rec_buf);
                mar_encode_table(L, &rec_buf, idx);

                buf_write(L, (const char*)&tag, MAR_CHR, buf);
                buf_write(L, (const char*)&rec_buf.head, MAR_I32, buf);
		        buf_write(L, rec_buf.data, rec_buf.head, buf);
		        buf_done(L, &rec_buf);
            }
            else {
                luaL_error(L, "attempt to encode userdata (no __persist hook)");
            }
            lua_pop(L, 1);
        }
        break;
    }
    case LUA_TNIL: break;
    default:
        luaL_error(L, "invalid value type (%s)", lua_typename(L, val_type));
    }
    lua_pop(L, 1);
}
コード例 #18
0
ファイル: LuaMaterial.cpp プロジェクト: Liuyangbiao/spring
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());
	}
}
コード例 #19
0
ファイル: lsNativeInterface.cpp プロジェクト: bagobor/TinyLS
void NativeInterface::managedPointerReleased(void *entry, int version)
{
    lua_State **_L = handleEntryToLuaState.get(entry);

    if (!_L)
    {
        return;
    }

    lua_State *L = *_L;

    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDVERSION);

    lua_pushlightuserdata(L, entry);
    lua_pushnil(L);
    lua_settable(L, -3);

    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDUSERDATA);
    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDNATIVESCRIPT);

    lua_pushlightuserdata(L, entry);
    lua_gettable(L, -3); // get from userdata
    if (!lua_isnil(L, -1))
    {
        lua_pushvalue(L, -1);
        lua_gettable(L, -3);

        assert(lua_istable(L, -1));

        // clear the instance table of any values
        // this will force the deleted managed metatable
        // to trip on access (once set below)
        int tidx = lua_gettop(L);

        lua_newtable(L);

        int clearTableIdx  = tidx + 1;
        int numClearValues = 0;

        lua_pushnil(L); /* first key */

        while (lua_next(L, tidx) != 0)
        {
            if (lua_isnumber(L, -2))
            {
                // We want to keep basic info in the (deleted) instance
                int indexer = (int)lua_tonumber(L, -2);

                if ((indexer == LSINDEXNATIVE) || (indexer == LSINDEXTYPE))
                {
                    lua_pop(L, 1); // pop value
                    continue;
                }
            }

            // push the key
            lua_pushvalue(L, -2);
            lua_rawseti(L, clearTableIdx, numClearValues++);

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

        // now run through the clearTable which holds the instance keys as values
        // and null out the instance keys

        for (int i = 0; i < numClearValues; i++)
        {
            lua_rawgeti(L, clearTableIdx, i);
            lua_pushnil(L);
            lua_settable(L, tidx);
        }

        lua_settop(L, tidx);

        lua_pushboolean(L, 1);
        lua_rawseti(L, tidx, LSINDEXDELETEDMANAGED);

        // mark managed instance as deleted
        // this replaces the metatable of the instance
        // with the deleted managed metatable which
        // provides errors on access
        luaL_getmetatable(L, LSDELETEDMANAGED);
        lua_setmetatable(L, -2);
        lua_pop(L, 1);

        lua_pushnil(L);
        lua_settable(L, -3); // clear from script
    }

    lua_pop(L, 1);
    // pop managed script

    lua_pushlightuserdata(L, entry);
    lua_pushnil(L);
    lua_settable(L, -3);

    lua_pop(L, 2);
}
コード例 #20
0
ファイル: CLuaPickupDefs.cpp プロジェクト: 50p/multitheftauto
int CLuaPickupDefs::setPickupType ( lua_State* luaVM )
{
    // The first 2 are always numeric saying weapon/health/armor
    int iArgument1 = lua_type ( luaVM, 1 );
    int iArgument2 = lua_type ( luaVM, 2 );
    int iArgument3 = lua_type ( luaVM, 3 );
    if ( ( iArgument1 == LUA_TLIGHTUSERDATA ) &&
         ( iArgument2 == LUA_TNUMBER || iArgument2 == LUA_TSTRING ) &&
         ( iArgument3 == LUA_TNUMBER || iArgument3 == LUA_TSTRING ) )
    {
        CElement* pElement = lua_toelement ( luaVM, 1 );
        if ( pElement )
        {
            // Do it
            if ( CStaticFunctionDefinitions::SetPickupType ( pElement, static_cast < unsigned char > ( lua_tonumber ( luaVM, 2 ) ), lua_tonumber ( luaVM, 3 ), lua_tonumber ( luaVM, 4 ) ) )
            {
                lua_pushboolean ( luaVM, true );
                return 1;
            }
        }
        else
            m_pScriptDebugging->LogBadPointer ( luaVM, "setPickupType", "element", 1 );
    }
    else
        m_pScriptDebugging->LogBadType ( luaVM, "setPickupType" );

    lua_pushboolean ( luaVM, false );
    return 1;
}
コード例 #21
0
ファイル: options.cpp プロジェクト: cpehle/lean
static int options_update_double(lua_State * L) {
    return push_options(L, to_options(L, 1).update(to_name_ext(L, 2), lua_tonumber(L, 3)));
}
コード例 #22
0
ファイル: CLuaPickupDefs.cpp プロジェクト: 50p/multitheftauto
int CLuaPickupDefs::createPickup ( lua_State* luaVM )
{
    // Grab all the argument types
    int iArgument1 = lua_type ( luaVM, 1 );
    int iArgument2 = lua_type ( luaVM, 2 );
    int iArgument3 = lua_type ( luaVM, 3 );
    int iArgument4 = lua_type ( luaVM, 4 );
    int iArgument5 = lua_type ( luaVM, 5 );
    int iArgument6 = lua_type ( luaVM, 6 );
    int iArgument7 = lua_type ( luaVM, 7 );

    // The first 6 are always numeric saying position, type and weapon/health/armor
    // TODO: Check argument 7 incase type is weapon
    if ( ( iArgument1 == LUA_TNUMBER || iArgument1 == LUA_TSTRING ) &&
         ( iArgument2 == LUA_TNUMBER || iArgument2 == LUA_TSTRING ) &&
         ( iArgument3 == LUA_TNUMBER || iArgument3 == LUA_TSTRING ) &&
         ( iArgument4 == LUA_TNUMBER || iArgument4 == LUA_TSTRING ) &&
         ( iArgument5 == LUA_TNUMBER || iArgument5 == LUA_TSTRING ) &&
         ( iArgument6 == LUA_TNUMBER || iArgument6 == LUA_TSTRING || iArgument6 == LUA_TNONE ) &&
         ( iArgument7 == LUA_TNUMBER || iArgument7 == LUA_TSTRING || iArgument7 == LUA_TNONE ) )
    {
        // Populate a position vector for it
        CVector vecPosition = CVector ( static_cast < float > ( lua_tonumber ( luaVM, 1 ) ),
                                        static_cast < float > ( lua_tonumber ( luaVM, 2 ) ),
                                        static_cast < float > ( lua_tonumber ( luaVM, 3 ) ) );

        // Is the type health or armor?
        unsigned long ulRespawnInterval = 30000;
        double dblAmmo = 50.0;
        if ( iArgument6 == LUA_TNUMBER || iArgument6 == LUA_TSTRING )
            ulRespawnInterval = static_cast < unsigned long > ( lua_tonumber ( luaVM, 6 ) );

        if ( iArgument7 == LUA_TNUMBER || iArgument7 == LUA_TSTRING )
            dblAmmo = lua_tonumber ( luaVM, 7 );

		CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM );
		if ( pLuaMain )
		{
			CResource* pResource = pLuaMain->GetResource();
			if ( pResource )
			{
				CPickup* pPickup = CStaticFunctionDefinitions::CreatePickup ( 
										pResource,
										vecPosition, 
										static_cast < unsigned char > ( lua_tonumber ( luaVM, 4 ) ), 
										lua_tonumber ( luaVM, 5 ), 
										ulRespawnInterval, 
										dblAmmo );
		        if ( pPickup )
		        {
					CElementGroup * pGroup = pResource->GetElementGroup();
					if ( pGroup )
					{
						pGroup->Add ( pPickup );
					}
					// Return the handle
					lua_pushelement ( luaVM, pPickup );
					return 1;
				}
			}
        }
    }
    else
        m_pScriptDebugging->LogBadType ( luaVM, "createPickup" );

    lua_pushboolean ( luaVM, false );
    return 1;
}
コード例 #23
0
ファイル: CCLuaStack.cpp プロジェクト: 2016Go/TF2016-NEW
int LuaStack::executeFunctionReturnArray(int handler,int numArgs,int numResults,__Array& resultArray)
{
    int top = lua_gettop(_state);
    if (pushFunctionByHandler(handler))                 /* L: ... arg1 arg2 ... func */
    {
        if (numArgs > 0)
        {
            lua_insert(_state, -(numArgs + 1));         /* L: ... func arg1 arg2 ... */
        }
        int functionIndex = -(numArgs + 1);
        if (!lua_isfunction(_state, functionIndex))
        {
            CCLOG("value at stack [%d] is not function", functionIndex);
            lua_pop(_state, numArgs + 1); // remove function and arguments
            lua_settop(_state,top);
            return 0;
        }
        
        int traceback = 0;
        lua_getglobal(_state, "__G__TRACKBACK__");                         /* L: ... func arg1 arg2 ... G */
        if (!lua_isfunction(_state, -1))
        {
            lua_pop(_state, 1);                                            /* L: ... func arg1 arg2 ... */
        }
        else
        {
            lua_insert(_state, functionIndex - 1);                         /* L: ... G func arg1 arg2 ... */
            traceback = functionIndex - 1;
        }
        
        int error = 0;
        ++_callFromLua;
        error = lua_pcall(_state, numArgs, numResults, traceback);                  /* L: ... [G] ret1 ret2 ... retResults*/
        --_callFromLua;
        if (error)
        {
            if (traceback == 0)
            {
                CCLOG("[LUA ERROR] %s", lua_tostring(_state, - 1));        /* L: ... error */
                lua_pop(_state, 1); // remove error message from stack
            }
            else                                                            /* L: ... G error */
            {
                lua_pop(_state, 2); // remove __G__TRACKBACK__ and error message from stack
            }
            lua_settop(_state,top);
            return 0;
        }
        
        // get return value,don't pass LUA_MULTRET to numResults,
        if (numResults <= 0)
        {
            lua_settop(_state,top);
            return 0;
        }
        
        for (int i = 0 ; i < numResults; i++)
        {
            if (lua_type(_state, -1) == LUA_TBOOLEAN) {
                
                bool value = lua_toboolean(_state, -1);
                resultArray.addObject(Bool::create(value)) ;
                
            }else if (lua_type(_state, -1) == LUA_TNUMBER) {
                
                double value = lua_tonumber(_state, -1);
                resultArray.addObject(Double::create(value));
                
            }else if (lua_type(_state, -1) == LUA_TSTRING) {
                
                const char* value = lua_tostring(_state, -1);
                resultArray.addObject(String::create(value));
                
            }else{
                
                resultArray.addObject(static_cast<Ref*>(tolua_tousertype(_state, -1, nullptr)));
            }
            // remove return value from stack
            lua_pop(_state, 1);                                                /* L: ... [G] ret1 ret2 ... ret*/
        }
        /* L: ... [G]*/
        
        if (traceback)
        {
            lua_pop(_state, 1); // remove __G__TRACKBACK__ from stack      /* L: ... */
        }
    }
    lua_settop(_state,top);
    return 1;
}
コード例 #24
0
ファイル: controllerbinder.cpp プロジェクト: Nlcke/gideros
static int getControllerName(lua_State *L)
{
    Controller *c = getInstance(L, 1);
	lua_pushstring(L, c->getControllerName(lua_tonumber(L, 2)));
    return 1;
}
コード例 #25
0
static int l_setcrossover(lua_State* L)
{
	LUA_PREAMBLE(MagnetostaticCuda, mag, 1);
	mag->crossover_tolerance = lua_tonumber(L, 2);
	return 0;
}
コード例 #26
0
ファイル: controllerbinder.cpp プロジェクト: Nlcke/gideros
static int vibrate(lua_State *L)
{
    Controller *c = getInstance(L, 1);
	c->vibrate(lua_tonumber(L, 2), lua_tonumber(L, 3));
    return 0;
}
コード例 #27
0
ファイル: PlayerBullet.cpp プロジェクト: chn22/OSGCC6
int plblt_getPos(lua_State *L) {
	plbltPos.x = lua_tonumber(L, 1);
	plbltPos.y = lua_tonumber(L, 2);
	lua_pop(L, 2);
	return 0;
}
コード例 #28
0
ファイル: luamodule.c プロジェクト: alexsilva/luapython
/*
** Used to create a Python Tuple from the parameters of a Lua function and/or
** to create a Python Tuple from the return values of a Lua function.
** Because the multiple return values are tied together as a Tuple, Python never
** sees Lua functions returning more than 1 value: the Tuple. All values are inside it.
*/
static PyObject *luaStack_to_pythonTuple(lua_State *L, int stack_start, int nelements) {
int n;
PyObject *tuple;
int item;
VALUE_TYPES type;
BOOLEAN succeed;

   tuple = PyTuple_New(nelements);

   succeed = True;

   /* values: Lua --> Python */
   for (n = 0; n < nelements; n++) {
      item = n+stack_start;
      type = luaGetType(L, item);

      switch (type) {

         case (Nothing):
            PyTuple_SetItem(tuple, n, Py_None);
            break;

         case (Number):
            PyTuple_SetItem(tuple, n, PyFloat_FromDouble(lua_tonumber(L, item)));
            break;

         case (String):
            PyTuple_SetItem(tuple, n, PyString_FromString(lua_tostring(L, item)));
            break;

         case (Function):
            PyTuple_SetItem(tuple, n, Py_None);
            PyErr_SetString(PyExc_Exception, "LuaPy: passing Lua functions to Python is not implemented. Sorry.");
            succeed = False;
            break;

         case (Pointer):
            PyTuple_SetItem(tuple, n, PyCObject_FromVoidPtr(lua_touserdata(L, item), NULL));
            break;

         case (Container): {
         PyObject *function;
            if ((lua_tag(L, item) == luaGetPythonFunctionTag(L))) {
               /* lua table that represents a python function --> python function */
               function = luaGetPythonFunctionFromLuaTable(L, item);
               /* ** FALTA IMPLEMENTAR O DECREF CORRESPONDENTE NO GC DE LUA! ** */
               Py_INCREF(function);
               PyTuple_SetItem(tuple, n, function);

            } else {
               PyTuple_SetItem(tuple, n, Py_None);
               PyErr_SetString(PyExc_Exception, "LuaPy: passing Lua tables to Python (as a tuples) is not implemented. Sorry.");
               succeed = False;
            }
            break;
         }

         default:
            PyTuple_SetItem(tuple, n, Py_None);
            PyErr_SetString(PyExc_Exception, "LuaPy: can't translate an unknown type of parameter or return value from Lua to Python");
            succeed = False;
      }

   }

   if (succeed) {
      return tuple;
   } else {
      return NULL;
   }
}
コード例 #29
0
ファイル: objectbuf.c プロジェクト: luafan/luafan
LUA_API int luafan_objectbuf_encode(lua_State *L)
{
  int obj_index = 1;
  int sym_idx = 0;
  if (lua_isnoneornil(L, 1))
  {
    luaL_error(L, "no argument.");
    return 0;
  }
  if (lua_istable(L, 2))
  {
    sym_idx = 2;
  }

  if (lua_isboolean(L, 1))
  {
    int value = lua_toboolean(L, 1);
    lua_pushstring(L, value ? "\x01" : "\x00");
    return 1;
  }

  CTX ctx = {0};
  ctx_init(&ctx, L);

  packer(L, &ctx, obj_index);

  uint8_t flag = 0;
  BYTEARRAY bodystream;
  bytearray_alloc(&bodystream, 64);
  bytearray_write8(&bodystream, flag); // place holder.

  lua_newtable(L);
  int index_map_idx = lua_gettop(L);
  uint32_t index = 2;

  if (!sym_idx)
  {
    lua_newtable(L);
  }
  else
  {
    lua_rawgeti(L, sym_idx, SYM_INDEX_INDEX);
    index = lua_tointeger(L, -1);
    lua_pop(L, 1);

    lua_rawgeti(L, sym_idx, SYM_INDEX_MAP);
  }
  int sym_map_idx = lua_gettop(L);

  lua_pushboolean(L, false);
  lua_pushinteger(L, FALSE_INDEX);
  lua_rawset(L, index_map_idx);

  lua_pushboolean(L, true);
  lua_pushinteger(L, TRUE_INDEX);
  lua_rawset(L, index_map_idx);

  // ---------------------------------------------------------------------------
  if (ctx.number_count > 0)
  {
    flag |= HAS_NUMBER_MASK;
    uint32_t realcount = 0;

    BYTEARRAY d;
    bytearray_alloc(&d, 0);

    lua_rawgeti(L, ctx.index, CTX_INDEX_NUMBERS);
    int i = 1;
    for (; i <= ctx.number_count; i++)
    {
      lua_rawgeti(L, -1, i);

      lua_pushvalue(L, -1);
      lua_rawget(L, sym_map_idx);
      if (lua_isnil(L, -1))
      {
        lua_pop(L, 1);
        ffi_stream_add_d64(&d, lua_tonumber(L, -1));
        lua_pushinteger(L, index + (++realcount));
        lua_rawset(L, index_map_idx);
      }
      else
      {
        lua_pop(L, 2); // pop sym number idx & number
      }
    }
    lua_pop(L, 1);

    ffi_stream_add_u30(&bodystream, realcount);
    bytearray_read_ready(&d);
    bytearray_writebuffer(&bodystream, d.buffer, d.total);

    bytearray_dealloc(&d);

    index += realcount;
  }

  // ---------------------------------------------------------------------------
  if (ctx.u30_count > 0)
  {
    flag |= HAS_U30_MASK;
    uint32_t realcount = 0;

    BYTEARRAY d;
    bytearray_alloc(&d, 0);

    lua_rawgeti(L, ctx.index, CTX_INDEX_U30S);
    int i = 1;
    for (; i <= ctx.u30_count; i++)
    {
      lua_rawgeti(L, -1, i);

      lua_pushvalue(L, -1);
      lua_rawget(L, sym_map_idx);
      if (lua_isnil(L, -1))
      {
        lua_pop(L, 1);
        ffi_stream_add_u30(&d, lua_tointeger(L, -1));
        lua_pushinteger(L, index + (++realcount));
        lua_rawset(L, index_map_idx);
      }
      else
      {
        lua_pop(L, 2); // pop sym u30 idx & u30
      }
    }
    lua_pop(L, 1);

    ffi_stream_add_u30(&bodystream, realcount);
    bytearray_read_ready(&d);
    bytearray_writebuffer(&bodystream, d.buffer, d.total);

    bytearray_dealloc(&d);

    index += realcount;
  }

  // ---------------------------------------------------------------------------
  if (ctx.string_count > 0)
  {
    flag |= HAS_STRING_MASK;
    uint32_t realcount = 0;

    BYTEARRAY d;
    bytearray_alloc(&d, 0);

    lua_rawgeti(L, ctx.index, CTX_INDEX_STRINGS);
    int i = 1;
    for (; i <= ctx.string_count; i++)
    {
      lua_rawgeti(L, -1, i);

      lua_pushvalue(L, -1);
      lua_rawget(L, sym_map_idx);
      if (lua_isnil(L, -1))
      {
        lua_pop(L, 1);
        size_t len;
        const char *buf = lua_tolstring(L, -1, &len);
        ffi_stream_add_string(&d, buf, len);
        lua_pushinteger(L, index + (++realcount));
        lua_rawset(L, index_map_idx);
      }
      else
      {
        lua_pop(L, 2); // pop sym u30 idx & u30
      }
    }
    lua_pop(L, 1);

    ffi_stream_add_u30(&bodystream, realcount);
    bytearray_read_ready(&d);
    bytearray_writebuffer(&bodystream, d.buffer, d.total);

    bytearray_dealloc(&d);

    index += realcount;
  }
  // ---------------------------------------------------------------------------
  if (ctx.table_count)
  {
    flag |= HAS_TABLE_MASK;
    ffi_stream_add_u30(&bodystream, ctx.table_count);

    lua_rawgeti(L, ctx.index, CTX_INDEX_TABLES);
    int i = 1;
    for (; i <= ctx.table_count; i++)
    {
      lua_rawgeti(L, -1, i);
      lua_pushinteger(L, index + i);
      lua_rawset(L, index_map_idx);
    }

    for (i = 1; i <= ctx.table_count; i++)
    {
      lua_rawgeti(L, -1, i);
      int tb_idx = lua_gettop(L);

      BYTEARRAY d;
      bytearray_alloc(&d, 0);

      int tb_count = 0;
      while (true)
      {
        lua_rawgeti(L, tb_idx, tb_count + 1);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          break;
        }
        tb_count++;

        int value_idx = lua_gettop(L);
        lua_pushvalue(L, value_idx);
        lua_rawget(L, sym_map_idx);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          lua_pushvalue(L, value_idx);
          lua_rawget(L, index_map_idx);
        }
        ffi_stream_add_u30(&d, lua_tointeger(L, -1));
        lua_pop(L, 1);

        lua_pop(L, 1);
      }

      lua_pushnil(L);
      while (lua_next(L, tb_idx) != 0)
      {
        int value_idx = lua_gettop(L);
        int key_idx = lua_gettop(L) - 1;

        // ignore previously added array part.
        lua_Number value = lua_tonumber(L, -2);
        // suppose index no more than max int.
        if (value == (int)value && value <= tb_count && value > 0)
        {
          lua_pop(L, 1);
          continue;
        }

        // d:AddU30(sym_map[k] or index_map[k])
        lua_pushvalue(L, key_idx);
        lua_rawget(L, sym_map_idx);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          lua_pushvalue(L, key_idx);
          lua_rawget(L, index_map_idx);
        }
        ffi_stream_add_u30(&d, lua_tointeger(L, -1));
        lua_pop(L, 1);

        // d:AddU30(sym_map[v] or index_map[v])
        lua_pushvalue(L, value_idx);
        lua_rawget(L, sym_map_idx);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          lua_pushvalue(L, value_idx);
          lua_rawget(L, index_map_idx);
        }
        ffi_stream_add_u30(&d, lua_tointeger(L, -1));
        lua_pop(L, 1);

        lua_pop(L, 1);
      }

      lua_pop(L, 1);

      bytearray_read_ready(&d);

      BYTEARRAY d2;
      bytearray_alloc(&d2, 0);
      ffi_stream_add_u30(&d2, tb_count);
      bytearray_read_ready(&d2);

      ffi_stream_add_u30(&bodystream, d.total + d2.total);
      ffi_stream_add_bytes(&bodystream, (const char *)d2.buffer, d2.total);
      ffi_stream_add_bytes(&bodystream, (const char *)d.buffer, d.total);

      bytearray_dealloc(&d2);
      bytearray_dealloc(&d);
    }
    lua_pop(L, 1);
  }

  bytearray_read_ready(&bodystream);
  *((uint8_t *)bodystream.buffer) = flag;
  lua_pushlstring(L, (const char *)bodystream.buffer, bodystream.total);

  bytearray_dealloc(&bodystream);
  return 1;
}
コード例 #30
0
ファイル: lua_named_arg.c プロジェクト: DHfly/S4
int lua_arg_parse_ctensor3(lua_State *L, int index, const char *argname, double *m){
	int i, j, k, l, ikind = 0;
	for(i = 0; i < 18; ++i){ m[i] = 0.; }
	if(lua_isnumber(L, index)){
		m[0] = lua_tonumber(L, index);
		m[8] = m[0];
		m[16] = m[0];
		return 0;
	}else if(!lua_istable(L, index)){
		return lua_arg_parse_ctensor3_err();
	}
	
	if(index < 0){ index += 1+lua_gettop(L); }
	lua_len(L, index); l = lua_tointeger(L, -1); lua_pop(L, 1);
	if(2 == l){ /* complex number */
		for(k = 0; k < 2; ++k){
			lua_pushinteger(L, k+1);
			lua_gettable(L, index);
			if(!lua_isnumber(L, -1)){
				return lua_named_arg_error(L, index, argname, "non-numeric value in what looks like a complex number");
			}
			m[k] = lua_tonumber(L, -1);
			lua_pop(L, 1);
		}
		m[8] = m[0];
		m[9] = m[1];
		m[16] = m[0];
		m[17] = m[1];
		return 0;
	}else if(3 != l){
		return lua_arg_parse_ctensor3_err();
	}
	/* Now we should expect a 3 vector or a 3x3 matrix */
	/* Iterate over the rows */
	for(i = 0; i < 3; ++i){
		lua_pushinteger(L, i+1);
		lua_gettable(L, index);
		
		if(0 == ikind){
			if(lua_isnumber(L, -1)){
				ikind = 1;
			}else if(!lua_istable(L, -1)){
				return lua_arg_parse_ctensor3_err();
			}else{
				lua_len(L, -1); l = lua_tointeger(L, -1); lua_pop(L, 1);
				if(2 == l){
					ikind = 2;
				}else if(3 == l){
					ikind = 3;
				}else{
					return lua_arg_parse_ctensor3_err();
				}
			}
		}
		
		if(1 == ikind){ /* real diagonal (3-vector) */
			if(!lua_isnumber(L, -1)){ return lua_arg_parse_ctensor3_err(); }
			m[8*i] = lua_tonumber(L, -1);
		}else if(2 == ikind){ /* complex diagonal (3-cvector) */
			if(!lua_istable(L, -1)){ return lua_arg_parse_ctensor3_err(); }
			lua_len(L, -1); l = lua_tointeger(L, -1); lua_pop(L, 1);
			if(2 != l){ return lua_arg_parse_ctensor3_err(); }
			for(k = 0; k < 2; ++k){
				lua_pushinteger(L, k+1);
				lua_gettable(L, -2);
				m[8*i+k] = lua_tonumber(L, -1);
				lua_pop(L, 1);
			}
		}else if(3 == ikind){ /* 3x3 matrix */
			int jkind = 0;
			if(!lua_istable(L, -1)){ return lua_arg_parse_ctensor3_err(); }
			lua_len(L, -1); l = lua_tointeger(L, -1); lua_pop(L, 1);
			if(3 != l){ return lua_arg_parse_ctensor3_err(); }
			for(j = 0; j < 3; ++j){
				lua_pushinteger(L, j+1);
				lua_gettable(L, -2);
				
				if(0 == jkind){
					if(lua_isnumber(L, -1)){
						jkind = 1;
					}else if(!lua_istable(L, -1)){
						return lua_arg_parse_ctensor3_err();
					}else{
						lua_len(L, -1); l = lua_tointeger(L, -1); lua_pop(L, 1);
						if(2 == l){
							jkind = 2;
						}else{
							return lua_arg_parse_ctensor3_err();
						}
					}
				}
				
				if(1 == jkind){ /* real diagonal (3-vector) */
					if(!lua_isnumber(L, -1)){ return lua_arg_parse_ctensor3_err(); }
					m[(i+j*3)*2] = lua_tonumber(L, -1);
				}else if(2 == jkind){ /* complex diagonal (3-cvector) */
					if(!lua_istable(L, -1)){ return lua_arg_parse_ctensor3_err(); }
					lua_len(L, -1); l = lua_tointeger(L, -1); lua_pop(L, 1);
					if(2 != l){ return lua_arg_parse_ctensor3_err(); }
					for(k = 0; k < 2; ++k){
						lua_pushinteger(L, k+1);
						lua_gettable(L, -2);
						m[k+(i+j*3)*2] = lua_tonumber(L, -1);
						lua_pop(L, 1);
					}
				}
				lua_pop(L, 1);
			}
		}
		
		lua_pop(L, 1);
		i++;
	}
	
	return 0;
}