Esempio n. 1
0
static int lua_iso8583_new(lua_State *L)
{
	struct iso8583 *iso8583h;
	iso8583_userdata *iso8583u = (iso8583_userdata *)lua_newuserdata(L, sizeof(iso8583_userdata));
	char error[BUFSIZ];

	iso8583u->handle = NULL;

	luaL_getmetatable(L, "iso8583");
	lua_setmetatable(L, -2);

	iso8583h = iso8583u->handle = iso8583_create();

	if (!iso8583h) {
		lua_pushnil(L);
		lua_pushstring(L, "alloc memory failed!");
		return 2;
	}

    if (lua_istable(L, 1)) {
    	lua_pushnil(L);  
		while (lua_next(L, 1) != 0)	{
			if (lua_isnumber(L, -2)) {
				int i = lua_tointeger(L, -2);

				if (i >= 0 && i <= 128) {
					if (lua_istable(L, -1)) {
						int size;
						int type;
						int align;
						int compress;
						char pad;
						
						// get size
						lua_getfield(L, -1, "size");
						
						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the size is not a number!", i);
							lua_pushstring(L, error);
							return 2;
						}

						size = lua_tointeger(L, -1);

						if (size < 0) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the size is little then 0! size = %d", i, size);
							lua_pushstring(L, error);
							return 2;
						}

						lua_pop(L, 1);

						// get type
						lua_getfield(L, -1, "type");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the type is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						type = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get align;
						lua_getfield(L, -1, "align");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the align is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						align = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get compress;
						lua_getfield(L, -1, "compress");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the compress is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						compress = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get pad;
						lua_getfield(L, -1, "pad");

						if (!lua_isstring(L, -1) || !lua_objlen(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the pad is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						pad = *lua_tostring(L, -1);

						lua_pop(L, 1);

						// define field
						if (iso8583_define(iso8583h, i, (unsigned int)size, pad, (unsigned int)type, 
											(unsigned int)align, (unsigned int)compress) != ISO8583_OK) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %u error! the field is invalid! size = %u, "
													"pad = %c, type = %u, align = %u, compress = %u!", 
										i, size, pad, type, align, compress);
							lua_pushstring(L, error);
							return 2;
						}
					}
				}
			}
			lua_pop(L, 1);
		}
	}

    return 1;
}
Esempio n. 2
0
/* Class index function
	* If the object is a userdata (ie, an object), it searches the field in
	* the alternative table stored in the corresponding "ubox" table.
*/
static int class_index_event (lua_State* L)
{
 int t = lua_type(L,1);
	if (t == LUA_TUSERDATA)
	{
		/* Access alternative table */
		#ifdef LUA_VERSION_NUM /* new macro on version 5.1 */
		lua_getfenv(L,1);
		if (!lua_rawequal(L, -1, TOLUA_NOPEER)) {
			lua_pushvalue(L, 2); /* key */
			lua_gettable(L, -2); /* on lua 5.1, we trade the "tolua_peers" lookup for a gettable call */
			if (!lua_isnil(L, -1))
				return 1;
		};
		#else
		lua_pushstring(L,"tolua_peers");
		lua_rawget(L,LUA_REGISTRYINDEX);        /* stack: obj key ubox */
		lua_pushvalue(L,1);
		lua_rawget(L,-2);                       /* stack: obj key ubox ubox[u] */
		if (lua_istable(L,-1))
		{
			lua_pushvalue(L,2);  /* key */
			lua_rawget(L,-2);                      /* stack: obj key ubox ubox[u] value */
			if (!lua_isnil(L,-1))
				return 1;
		}
		#endif
		lua_settop(L,2);                        /* stack: obj key */
		/* Try metatables */
		lua_pushvalue(L,1);                     /* stack: obj key obj */
		while (lua_getmetatable(L,-1))
		{                                       /* stack: obj key obj mt */
			lua_remove(L,-2);                      /* stack: obj key mt */
			if (lua_isnumber(L,2))                 /* check if key is a numeric value */
			{
				/* try operator[] */
				lua_pushstring(L,".geti");
				lua_rawget(L,-2);                      /* stack: obj key mt func */
				if (lua_isfunction(L,-1))
				{
					lua_pushvalue(L,1);
					lua_pushvalue(L,2);
					lua_call(L,2,1);
					return 1;
				}
			}
			else
			{
			 lua_pushvalue(L,2);                    /* stack: obj key mt key */
				lua_rawget(L,-2);                      /* stack: obj key mt value */
				if (!lua_isnil(L,-1))
					return 1;
				else
					lua_pop(L,1);
				/* try C/C++ variable */
				lua_pushstring(L,".get");
				lua_rawget(L,-2);                      /* stack: obj key mt tget */
				if (lua_istable(L,-1))
				{
					lua_pushvalue(L,2);
					lua_rawget(L,-2);                      /* stack: obj key mt value */
					if (lua_iscfunction(L,-1))
					{
						lua_pushvalue(L,1);
						lua_pushvalue(L,2);
						lua_call(L,2,1);
						return 1;
					}
					else if (lua_istable(L,-1))
					{
						/* deal with array: create table to be returned and cache it in ubox */
						void* u = *((void**)lua_touserdata(L,1));
						lua_newtable(L);                /* stack: obj key mt value table */
						lua_pushstring(L,".self");
						lua_pushlightuserdata(L,u);
						lua_rawset(L,-3);               /* store usertype in ".self" */
						lua_insert(L,-2);               /* stack: obj key mt table value */
						lua_setmetatable(L,-2);         /* set stored value as metatable */
						lua_pushvalue(L,-1);            /* stack: obj key met table table */
						lua_pushvalue(L,2);             /* stack: obj key mt table table key */
						lua_insert(L,-2);               /*  stack: obj key mt table key table */
						storeatubox(L,1);               /* stack: obj key mt table */
						return 1;
					}
				}
			}
			lua_settop(L,3);
		}
		lua_pushnil(L);
		return 1;
	}
	else if (t== LUA_TTABLE)
	{
		module_index_event(L);
		return 1;
	}
	lua_pushnil(L);
	return 1;
}
Esempio n. 3
0
static int openssl_ocsp_response(lua_State *L)
{
  OCSP_RESPONSE *res = NULL;

  if (lua_isstring(L, 1))
  {
    BIO* bio = load_bio_object(L, 1);
    res = d2i_OCSP_RESPONSE_bio(bio, NULL);
    /*
    BIO_reset(bio);
    if (!res)
    {
      res = PEM_read_bio_OCSP_RESPONSE(bio, NULL, NULL);
    }
    */
    BIO_free(bio);
  }
  else
  {
    ASN1_TIME* thispnd, *nextpnd;
    OCSP_CERTID *ca_id, *cid;
    OCSP_BASICRESP *bs;
    OCSP_REQUEST *req = CHECK_OBJECT(1, OCSP_REQUEST, "openssl.ocsp_request");
    X509* ca = CHECK_OBJECT(2, X509, "openssl.x509");
    X509* rcert = CHECK_OBJECT(3, X509, "openssl.x509");
    EVP_PKEY *rkey = CHECK_OBJECT(4, EVP_PKEY, "openssl.evp_pkey");

    unsigned long flag = luaL_optint(L, 6, 0);
    int nmin = luaL_optint(L, 7, 0);
    int nday = luaL_optint(L, 8, 1);
    STACK_OF(X509) *rother = lua_isnoneornil(L, 9) ? NULL : CHECK_OBJECT(9, STACK_OF(X509), "openssl.stack_of_x509");

    int i, id_count, type;
    BIO* bio = NULL;
    luaL_argcheck(L, openssl_pkey_is_private(rkey), 4, "must be private key");

    type = lua_type(L, 5);
    if (type != LUA_TFUNCTION && type != LUA_TTABLE)
    {
      luaL_error(L, "#5 must be a table or function that to get status of certificate");
    }
    bio = BIO_new(BIO_s_mem());
    ca_id = OCSP_cert_to_id(EVP_sha1(), NULL, ca);
    bs = OCSP_BASICRESP_new();
    thispnd = X509_gmtime_adj(NULL, 0);
    nextpnd = X509_gmtime_adj(NULL, nmin * 60 + nday * 3600 * 24);
    id_count = OCSP_request_onereq_count(req);

    for (i = 0; i < id_count; i++)
    {
      OCSP_ONEREQ  *one;
      ASN1_INTEGER *serial;
      ASN1_OBJECT* inst = NULL;
      ASN1_TIME* revtm = NULL;
      ASN1_GENERALIZEDTIME *invtm = NULL;
      OCSP_SINGLERESP *single = NULL;
      int reason = OCSP_REVOKED_STATUS_UNSPECIFIED, status = V_OCSP_CERTSTATUS_UNKNOWN;

      one = OCSP_request_onereq_get0(req, i);
      cid = OCSP_onereq_get0_id(one);
      if (OCSP_id_issuer_cmp(ca_id, cid))
      {
        OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN,
                               0, NULL, thispnd, nextpnd);
        continue;
      }
      OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);

      if (lua_istable(L, 5))
      {
        BUF_MEM *buf;
        BIO_reset(bio);
        i2a_ASN1_INTEGER(bio, serial);

        BIO_get_mem_ptr(bio, &buf);
        lua_pushlstring(L, buf->data, buf->length);
        lua_gettable(L, 5);
        if (lua_isnil(L, -1))
          status = V_OCSP_CERTSTATUS_UNKNOWN;
        else
        {
          luaL_checktype(L, -1, LUA_TTABLE);
          lua_getfield(L, -1, "revoked");
          if (lua_toboolean(L, -1))
          {
            lua_pop(L, 1);

            status = V_OCSP_CERTSTATUS_REVOKED;

            lua_getfield(L, -1, "revoked_time");
            if (!lua_isnil(L, -1))
            {
              revtm = ASN1_TIME_new();
              ASN1_TIME_set(revtm, luaL_checkint(L, -1));
            }
            lua_pop(L, 1);

            lua_getfield(L, -1, "reason");
            if (lua_isstring(L, -1))
              reason = openssl_s2i_revoke_reason(lua_tostring(L, -1));
            else
              reason = luaL_checkint(L, -1);
            lua_pop(L, 1);
          }
          else
          {
            lua_pop(L, 1);
            status = V_OCSP_CERTSTATUS_GOOD;
          }
        }
      }
      else
      {
        //TODO:
      }

      if (reason == 7)
        reason = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
      else if (reason == 8)
      {
        reason = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
        //inst = OBJ_txt2obj(str, 0);
      }
      else if (reason == 9 || reason == 10)
      {
        if ( reason == 9 )
          reason = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
        else if (reason == 10)
          reason = OCSP_REVOKED_STATUS_CACOMPROMISE;
        /*
        invtm = ASN1_GENERALIZEDTIME_new();
        if (!ASN1_GENERALIZEDTIME_set_string(invtm, arg_str))
        */
      }


      single = OCSP_basic_add1_status(bs, cid, status, reason, revtm, thispnd, nextpnd);


      if (invtm)
      {
        OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
        ASN1_TIME_free(revtm);
      }
      if (inst)
      {
        OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
        ASN1_OBJECT_free(inst);
      }
      if (invtm)
        ASN1_GENERALIZEDTIME_free(invtm);
    }
    OCSP_copy_nonce(bs, req);
    OCSP_basic_sign(bs, rcert, rkey, EVP_sha1(), rother, flag);

    res = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
    BIO_free(bio);
  }
  if (res)
  {
    PUSH_OBJECT(res, "openssl.ocsp_response");
  }
  else
    lua_pushnil(L);
  return 1;
}
int Thermal::help(lua_State* L)
{
	if(lua_gettop(L) == 0)
	{
		lua_pushstring(L, "Generates a the random thermal field of a *SpinSystem*");
		lua_pushstring(L, "1 *3Vector* or *SpinSystem*, 1 Optional *Random*: System Size and built in RNG"); 
		lua_pushstring(L, ""); //output, empty
		return 3;
	}
	
	if(lua_istable(L, 1))
	{
		return 0;
	}
	
	if(!lua_iscfunction(L, 1))
	{
		return luaL_error(L, "help expect zero arguments or 1 function.");
	}
	
	lua_CFunction func = lua_tocfunction(L, 1);
	
	if(func == l_apply)
	{
		lua_pushstring(L, "Generates a the random thermal field of a *SpinSystem*");
		lua_pushstring(L, "1 *SpinSystem*, 1 Optional *Random*,: The first argument is the spin system which will receive the field. The second optional argument is a random number generator that is used as a source of random values, if absent then the RNG supplied in the constructor will be used.");
		lua_pushstring(L, "");
		return 3;
	}

	if(func == l_scalesite)
	{
		lua_pushstring(L, "Scale the thermal field at a site. This allows non-uniform thermal effects over a lattice.");
		lua_pushstring(L, "1 *3Vector*, 1 Number: The vectors define the lattice sites that will have a scaled thermal effect, the number is the how the thermal field is scaled.");
		lua_pushstring(L, "");
		return 3;
	}
	
	if(func == l_settemp)
	{
		lua_pushstring(L, "Sets the base value of the temperature. ");
		lua_pushstring(L, "1 number: temperature of the system.");
		lua_pushstring(L, "");
		return 3;
	}
	
	if(func == l_gettemp)
	{
		lua_pushstring(L, "Gets the base value of the temperature. ");
		lua_pushstring(L, "");
		lua_pushstring(L, "1 number: temperature of the system.");
		return 3;
	}
	
	if(func == l_getscalearray)
	{
		lua_pushstring(L, "Get an array representing the thermal scale at each site. This array is connected to the Operator so changes to the returned array will change the Operator.");
		lua_pushstring(L, "");
		lua_pushstring(L, "1 Array: The thermal scale of the sites.");
		return 3;
	}
	if(func == l_setscalearray)
	{
		lua_pushstring(L, "Set an array representing the new thermal scale at each site.");
		lua_pushstring(L, "1 Array: The thermal scale of the sites.");
		lua_pushstring(L, "");
		return 3;
	}

	if(func == l_rng)
	{
		lua_pushstring(L, "Get the *Random* number generator supplied at initialization");
		lua_pushstring(L, "");
		lua_pushstring(L, "1 *Random* or 1 nil: RNG");
		return 3;
	}

	return SpinOperation::help(L);
}
Esempio n. 5
0
Entity *LuaScripting::LoadEntity(const char *_entityFile)
{
    if (RunScript(_entityFile)) {
        lua_getglobal(m_luaState, "name");
        if (lua_isstring(m_luaState, -1)) {
            Entity *e = new Entity(0, lua_tostring(m_luaState, -1));
            Vector position;
            position.x = position.y = 100;
            position.z = 0;
            e->SetProperty("position", TYPE_VECTOR, (void*)&position);
            lua_pop(m_luaState, 1);
            lua_getglobal(m_luaState, "properties");
            if (lua_istable(m_luaState, -1)) {
                lua_pushnil(m_luaState);
                while(lua_next(m_luaState, -2) != 0) {
                    const char *propertyName = NULL;
                    if (!lua_isnumber(m_luaState, -2) && lua_isstring(m_luaState, -2)) {
                        propertyName = lua_tostring(m_luaState, -2);
                        int type = lua_type(m_luaState, -1);
                        if (propertyName != NULL) {
                            switch (type) {
                            case LUA_TSTRING:
                                e->SetProperty(propertyName, TYPE_STRING, (void*)lua_tostring(m_luaState, -1));
                                break;
                            case LUA_TNUMBER: {
                                float f = lua_tonumber(m_luaState, -1);
                                e->SetProperty(propertyName, TYPE_NUMBER, (void*)&f);
                                break;
                            }
                            case LUA_TBOOLEAN: {
                                bool b = lua_toboolean(m_luaState, -1);
                                e->SetProperty(propertyName, TYPE_BOOLEAN, (void*)&b);
                                break;
                            }
                            case LUA_TUSERDATA:
                                if (lua_isusertype(m_luaState, -1, "Rect")) {
                                    e->SetProperty(propertyName, TYPE_RECT, tolua_tousertype(m_luaState, -1, 0));
                                    break;
                                } else if (lua_isusertype(m_luaState, -1, "Vector")) {
                                    e->SetProperty(propertyName, TYPE_VECTOR, tolua_tousertype(m_luaState, -1, 0));
                                    break;
                                } else {
                                    g_console->WriteLine("WARN: Unknown property type detected, please fix.");
                                }
                                break;
                            default:
                                g_console->WriteLine("WARN: Property values must one of the following types: String, Number, Boolean, Rect, Vector");
                                break;
                            }
                        }
                    }
                    lua_pop(m_luaState, 1);
                }
            }
            lua_getglobal(m_luaState, "behaviors");
            if (lua_istable(m_luaState, -1)) { // -1 is the table
                // Loop through behaviors table
                lua_pushnil(m_luaState); // -1 is the first key
                while(lua_next(m_luaState, -2) != 0) { // -2: behaviors table
                    const char *behaviorName = NULL;
                    if (!lua_isnumber(m_luaState, -1) && lua_isstring(m_luaState, -1)) {
                        behaviorName = lua_tostring(m_luaState, -1);
                    } else if (!lua_isnumber(m_luaState, -2) && lua_isstring(m_luaState, -2)) {
                        behaviorName = lua_tostring(m_luaState, -2);
                    } else {
                        g_console->WriteLine("WARN: Non-string entry found in behaviors table, please fix.");
                    }
                    if (behaviorName != NULL) {
                        behaviorFunc f = get_behavior(behaviorName);
                        if (f == NULL) {
                            g_console->WriteLine("WARN: '%s' is not a registered behavior.", behaviorName);
                        } else {
                            e->AddBehavior(behaviorName, f);
                        }
                    }
                    lua_pop(m_luaState, 1);
                }
            }
            /* Look for input hooks */
            /* onKeyUp */
            lua_getglobal(m_luaState, "onKeyUp");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(SDL_KEYUP, e);
            }
            /* onKeyDown */
            lua_getglobal(m_luaState, "onKeyDown");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(SDL_KEYDOWN, e);
            }
            /* onMouseDown */
            lua_getglobal(m_luaState, "onMouseDown");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(SDL_MOUSEBUTTONDOWN, e);
            }
            /* onMouseUp */
            lua_getglobal(m_luaState, "onMouseUp");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(SDL_MOUSEBUTTONUP, e);
            }
            /* onMouseOver */
            lua_getglobal(m_luaState, "onMouseOver");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(MOUSE_OVER, e);
            }
            /* onMouseLeave */
            lua_getglobal(m_luaState, "onMouseLeave");
            if (lua_isfunction(m_luaState, -1)) {
                g_input->RegisterEventObserver(MOUSE_LEAVE, e);
            }
            ResetEntityFileGlobals();
            return e;
        }
        ResetEntityFileGlobals();
        g_console->WriteLine("ERROR: Missing field: 'name'");
    }
    g_console->WriteLine("FAIL: Could not parse the entity file.");
    return NULL;
}
Esempio n. 6
0
bool read_schematic_def(lua_State *L, int index,
	Schematic *schem, std::vector<std::string> *names)
{
	if (!lua_istable(L, index))
		return false;

	//// Get schematic size
	lua_getfield(L, index, "size");
	v3s16 size = check_v3s16(L, -1);
	lua_pop(L, 1);

	schem->size = size;

	//// Get schematic data
	lua_getfield(L, index, "data");
	luaL_checktype(L, -1, LUA_TTABLE);

	int numnodes = size.X * size.Y * size.Z;
	schem->schemdata = new MapNode[numnodes];
	int i = 0;

	size_t names_base = names->size();
	std::map<std::string, content_t> name_id_map;

	lua_pushnil(L);
	while (lua_next(L, -2)) {
		if (i >= numnodes) {
			i++;
			lua_pop(L, 1);
			continue;
		}

		// same as readnode, except param1 default is MTSCHEM_PROB_CONST
		lua_getfield(L, -1, "name");
		std::string name = luaL_checkstring(L, -1);
		lua_pop(L, 1);

		u8 param1;
		lua_getfield(L, -1, "param1");
		param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
		lua_pop(L, 1);

		u8 param2;
		lua_getfield(L, -1, "param2");
		param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
		lua_pop(L, 1);

		std::map<std::string, content_t>::iterator it = name_id_map.find(name);
		content_t name_index;
		if (it != name_id_map.end()) {
			name_index = it->second;
		} else {
			name_index = names->size() - names_base;
			name_id_map[name] = name_index;
			names->push_back(name);
		}

		schem->schemdata[i] = MapNode(name_index, param1, param2);

		i++;
		lua_pop(L, 1);
	}

	if (i != numnodes) {
		errorstream << "read_schematic_def: incorrect number of "
			"nodes provided in raw schematic data (got " << i <<
			", expected " << numnodes << ")." << std::endl;
		return false;
	}

	//// Get Y-slice probability values (if present)
	schem->slice_probs = new u8[size.Y];
	for (i = 0; i != size.Y; i++)
		schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS;

	lua_getfield(L, index, "yslice_prob");
	if (lua_istable(L, -1)) {
		lua_pushnil(L);
		while (lua_next(L, -2)) {
			if (getintfield(L, -1, "ypos", i) && i >= 0 && i < size.Y) {
				schem->slice_probs[i] = getintfield_default(L, -1,
					"prob", MTSCHEM_PROB_ALWAYS);
			}
			lua_pop(L, 1);
		}
	}

	return true;
}
Esempio n. 7
0
static int player_set(lua_State *L)
{
	player_t *plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER));
	const char *field = luaL_checkstring(L, 2);
	if (!plr)
		return LUA_ErrInvalid(L, "player_t");

	if (hud_running)
		return luaL_error(L, "Do not alter player_t in HUD rendering code!");

	if (fastcmp(field,"mo")) {
		mobj_t *newmo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ));
		plr->mo->player = NULL; // remove player pointer from old mobj
		(newmo->player = plr)->mo = newmo; // set player pointer for new mobj, and set new mobj as the player's mobj
	}
	else if (fastcmp(field,"cmd"))
		return NOSET;
	else if (fastcmp(field,"playerstate"))
		plr->playerstate = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"viewz"))
		plr->viewz = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"viewheight"))
		plr->viewheight = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"deltaviewheight"))
		plr->deltaviewheight = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"bob"))
		plr->bob = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"aiming")) {
		plr->aiming = luaL_checkangle(L, 3);
		if (plr == &players[consoleplayer])
			localaiming = plr->aiming;
		else if (plr == &players[secondarydisplayplayer])
			localaiming2 = plr->aiming;
	}
	else if (fastcmp(field,"health"))
		plr->health = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"pity"))
		plr->pity = (SINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"currentweapon"))
		plr->currentweapon = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"ringweapons"))
		plr->ringweapons = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"powers"))
		return NOSET;
	else if (fastcmp(field,"pflags"))
		plr->pflags = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"panim"))
		plr->panim = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"flashcount"))
		plr->flashcount = (UINT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"flashpal"))
		plr->flashpal = (UINT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"skincolor"))
	{
		UINT8 newcolor = (UINT8)luaL_checkinteger(L,3);
		if (newcolor >= MAXSKINCOLORS)
			return luaL_error(L, "player.skincolor %d out of range (0 - %d).", newcolor, MAXSKINCOLORS-1);
		plr->skincolor = newcolor;
	}
	else if (fastcmp(field,"score"))
		plr->score = (UINT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"dashspeed"))
		plr->dashspeed = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"dashtime"))
		plr->dashtime = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"normalspeed"))
		plr->normalspeed = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"runspeed"))
		plr->runspeed = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"thrustfactor"))
		plr->thrustfactor = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"accelstart"))
		plr->accelstart = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"acceleration"))
		plr->acceleration = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"charability"))
		plr->charability = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"charability2"))
		plr->charability2 = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"charflags"))
		plr->charflags = (UINT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"thokitem"))
		plr->thokitem = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"spinitem"))
		plr->spinitem = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"revitem"))
		plr->revitem = luaL_checkinteger(L, 3);
	else if (fastcmp(field,"actionspd"))
		plr->actionspd = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"mindash"))
		plr->mindash = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"maxdash"))
		plr->maxdash = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"jumpfactor"))
		plr->jumpfactor = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"lives"))
		plr->lives = (SINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"continues"))
		plr->continues = (SINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"xtralife"))
		plr->xtralife = (SINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"gotcontinue"))
		plr->gotcontinue = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"speed"))
		plr->speed = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"jumping"))
		plr->jumping = luaL_checkboolean(L, 3);
	else if (fastcmp(field,"secondjump"))
		plr->secondjump = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"fly1"))
		plr->fly1 = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"scoreadd"))
		plr->scoreadd = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"glidetime"))
		plr->glidetime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"climbing"))
		plr->climbing = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"deadtimer"))
		plr->deadtimer = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"exiting"))
		plr->exiting = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"homing"))
		plr->homing = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"skidtime"))
		plr->skidtime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"cmomx"))
		plr->cmomx = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"cmomy"))
		plr->cmomy = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"rmomx"))
		plr->rmomx = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"rmomy"))
		plr->rmomy = luaL_checkfixed(L, 3);
	else if (fastcmp(field,"numboxes"))
		plr->numboxes = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"totalring"))
		plr->totalring = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"realtime"))
		plr->realtime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"laps"))
		plr->laps = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"ctfteam"))
		plr->ctfteam = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"gotflag"))
		plr->gotflag = (UINT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"weapondelay"))
		plr->weapondelay = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"tossdelay"))
		plr->tossdelay = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starpostx"))
		plr->starpostx = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starposty"))
		plr->starposty = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starpostz"))
		plr->starpostz = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starpostnum"))
		plr->starpostnum = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starposttime"))
		plr->starposttime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"starpostangle"))
		plr->starpostangle = luaL_checkangle(L, 3);
	else if (fastcmp(field,"angle_pos"))
		plr->angle_pos = luaL_checkangle(L, 3);
	else if (fastcmp(field,"old_angle_pos"))
		plr->old_angle_pos = luaL_checkangle(L, 3);
	else if (fastcmp(field,"axis1"))
		P_SetTarget(&plr->axis1, *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)));
	else if (fastcmp(field,"axis2"))
		P_SetTarget(&plr->axis2, *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)));
	else if (fastcmp(field,"bumpertime"))
		plr->bumpertime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"flyangle"))
		plr->flyangle = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"drilltimer"))
		plr->drilltimer = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"linkcount"))
		plr->linkcount = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"linktimer"))
		plr->linktimer = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"anotherflyangle"))
		plr->anotherflyangle = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"nightstime"))
		plr->nightstime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"drillmeter"))
		plr->drillmeter = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"drilldelay"))
		plr->drilldelay = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"bonustime"))
		plr->bonustime = luaL_checkboolean(L, 3);
	else if (fastcmp(field,"capsule"))
	{
		mobj_t *mo = NULL;
		if (!lua_isnil(L, 3))
			mo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ));
		P_SetTarget(&plr->capsule, mo);
	}
	else if (fastcmp(field,"mare"))
		plr->mare = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"marebegunat"))
		plr->marebegunat = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"startedtime"))
		plr->startedtime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"finishedtime"))
		plr->finishedtime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"finishedrings"))
		plr->finishedrings = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"marescore"))
		plr->marescore = (UINT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"lastmarescore"))
		plr->lastmarescore = (UINT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"lastmare"))
		plr->lastmare = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"maxlink"))
		plr->maxlink = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"texttimer"))
		plr->texttimer = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"textvar"))
		plr->textvar = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"lastsidehit"))
		plr->lastsidehit = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"lastlinehit"))
		plr->lastlinehit = (INT16)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"losstime"))
		plr->losstime = (tic_t)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"timeshit"))
		plr->timeshit = (UINT8)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"onconveyor"))
		plr->onconveyor = (INT32)luaL_checkinteger(L, 3);
	else if (fastcmp(field,"awayviewmobj"))
	{
		mobj_t *mo = NULL;
		if (!lua_isnil(L, 3))
			mo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ));
		P_SetTarget(&plr->awayviewmobj, mo);
	}
	else if (fastcmp(field,"awayviewtics"))
	{
		plr->awayviewtics = (INT32)luaL_checkinteger(L, 3);
		if (plr->awayviewtics && !plr->awayviewmobj) // awayviewtics must ALWAYS have an awayviewmobj set!!
			P_SetTarget(&plr->awayviewmobj, plr->mo); // but since the script might set awayviewmobj immediately AFTER setting awayviewtics, use player mobj as filler for now.
	}
	else if (fastcmp(field,"awayviewaiming"))
		plr->awayviewaiming = luaL_checkangle(L, 3);
	else if (fastcmp(field,"spectator"))
		plr->spectator = lua_toboolean(L, 3);
	else if (fastcmp(field,"bot"))
		return NOSET;
	else if (fastcmp(field,"jointime"))
		plr->jointime = (tic_t)luaL_checkinteger(L, 3);
#ifdef HWRENDER
	else if (fastcmp(field,"fovadd"))
		plr->fovadd = luaL_checkfixed(L, 3);
#endif
	else {
		lua_getfield(L, LUA_REGISTRYINDEX, LREG_EXTVARS);
		I_Assert(lua_istable(L, -1));
		lua_pushlightuserdata(L, plr);
		lua_rawget(L, -2);
		if (lua_isnil(L, -1)) {
			// This index doesn't have a table for extra values yet, let's make one.
			lua_pop(L, 1);
			CONS_Debug(DBG_LUA, M_GetText("'%s' has no field named '%s'; adding it as Lua data.\n"), "player_t", field);
			lua_newtable(L);
			lua_pushlightuserdata(L, plr);
			lua_pushvalue(L, -2); // ext value table
			lua_rawset(L, -4); // LREG_EXTVARS table
		}
		lua_pushvalue(L, 3); // value to store
		lua_setfield(L, -2, field);
		lua_pop(L, 2);
	}

	return 0;
}
Esempio n. 8
0
static void lua_to_image(lua_State * L, image * a)
{   /* value key table ... */
    int i;
    image_dict *d = img_dict(a);
    assert(d != NULL);
    lua_pushstring(L, IMG_ENV); /* s v k t ... */
    lua_gettable(L, LUA_REGISTRYINDEX); /* t v k t ... */
    lua_pushvalue(L, -3);       /* k t v k t ... */
    lua_gettable(L, -2);        /* i? t v k t ... */
    if (!lua_isnumber(L, -1))   /* !i t v k t ... */
        luaL_error(L, "lua_to_image(): %s is not a valid image key",
                   lua_tostring(L, -4));
    i = (int) lua_tointeger(L, -1);     /* i t v k t ... */
    lua_pop(L, 2);              /* v k t ... */
    switch (i) {
    case P_WIDTH:
        if (lua_isnil(L, -1))
            set_wd_running(a);
        else if (lua_type(L, -1) == LUA_TNUMBER)
            img_width(a) = (int) lua_tointeger(L, -1);
        else if (lua_type(L, -1) == LUA_TSTRING)
            img_width(a) = dimen_to_number(L, lua_tostring(L, -1));
        else
            luaL_error(L,
                       "image.width needs integer or nil value or dimension string");
        break;
    case P_HEIGHT:
        if (lua_isnil(L, -1))
            set_ht_running(a);
        else if (lua_type(L, -1) == LUA_TNUMBER)
            img_height(a) = (int) lua_tointeger(L, -1);
        else if (lua_type(L, -1) == LUA_TSTRING)
            img_height(a) = dimen_to_number(L, lua_tostring(L, -1));
        else
            luaL_error(L,
                       "image.height needs integer or nil value or dimension string");
        break;
    case P_DEPTH:
        if (lua_isnil(L, -1))
            set_dp_running(a);
        else if (lua_type(L, -1) == LUA_TNUMBER)
            img_depth(a) = (int) lua_tointeger(L, -1);
        else if (lua_type(L, -1) == LUA_TSTRING)
            img_depth(a) = dimen_to_number(L, lua_tostring(L, -1));
        else
            luaL_error(L,
                       "image.depth needs integer or nil value or dimension string");
        break;
    case P_TRANSFORM:
        if (lua_isnumber(L, -1))
            img_transform(a) = (int) lua_tointeger(L, -1);
        else
            luaL_error(L, "image.transform needs integer value");
        break;
    /* now follow all image_dict entries */
    case P_FILENAME:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.filename is now read-only");
        if (img_type(d) == IMG_TYPE_PDFSTREAM)
            luaL_error(L, "image.filename can't be used with image.stream");
        if (lua_isstring(L, -1)) {
            xfree(img_filename(d));
            img_filename(d) = xstrdup(lua_tostring(L, -1));
        } else
            luaL_error(L, "image.filename needs string value");
        break;
    case P_VISIBLEFILENAME:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.visiblefilename is now read-only");
        if (img_type(d) == IMG_TYPE_PDFSTREAM)
            luaL_error(L,
                       "image.visiblefilename can't be used with image.stream");
        if (lua_isstring(L, -1)) {
            xfree(img_visiblefilename(d));
            img_visiblefilename(d) = xstrdup(lua_tostring(L, -1));
        } else
            luaL_error(L, "image.visiblefilename needs string value");
        break;
    case P_ATTR:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.attr is now read-only");
        if (lua_isstring(L, -1) || lua_isnil(L, -1)) {
            xfree(img_attr(d));
            if (lua_isstring(L, -1))
                img_attr(d) = xstrdup(lua_tostring(L, -1));
        } else
            luaL_error(L, "image.attr needs string or nil value");
        break;
    case P_PAGE:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.page is now read-only");
        if (lua_type(L, -1) == LUA_TSTRING) {
            xfree(img_pagename(d));
            img_pagename(d) = xstrdup(lua_tostring(L, -1));
            img_pagenum(d) = 0;
        } else if (lua_type(L, -1) == LUA_TNUMBER) {
            img_pagenum(d) = (int) lua_tointeger(L, -1);
            xfree(img_pagename(d));
        } else
            luaL_error(L, "image.page needs integer or string value");
        break;
    case P_COLORSPACE:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.colorspace is now read-only");
        if (lua_isnil(L, -1))
            img_colorspace(d) = 0;
        else if (lua_isnumber(L, -1))
            img_colorspace(d) = (int) lua_tointeger(L, -1);
        else
            luaL_error(L, "image.colorspace needs integer or nil value");
        break;
    case P_PAGEBOX:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.pagebox is now read-only");
        if (lua_isnil(L, -1))
            img_pagebox(d) = PDF_BOX_SPEC_NONE;
        else if (lua_isstring(L, -1))
            img_pagebox(d) = luaL_checkoption(L, -1, "none", pdfboxspec_s);
        else
            luaL_error(L, "image.pagebox needs string or nil value");
        break;
    case P_BBOX:
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.bbox is now read-only");
        if (!lua_istable(L, -1))
            luaL_error(L, "image.bbox needs table value");
        if (lua_rawlen(L, -1) != 4)
            luaL_error(L, "image.bbox table must have exactly 4 elements");
        for (i = 1; i <= 4; i++) {      /* v k t ... */
            lua_pushinteger(L, i);      /* idx v k t ... */
            lua_gettable(L, -2);        /* int v k t ... */
            if (lua_type(L, -1) == LUA_TNUMBER)
                img_bbox(d)[i - 1] = (int) lua_tointeger(L, -1);
            else if (lua_type(L, -1) == LUA_TSTRING)
                img_bbox(d)[i - 1] = dimen_to_number(L, lua_tostring(L, -1));
            else
                luaL_error(L,
                           "image.bbox table needs integer value or dimension string elements");
            lua_pop(L, 1);      /* v k t ... */
        }
        img_set_bbox(d);
        break;
    case P_STREAM:
        if (img_filename(d) != NULL)
            luaL_error(L, "image.stream can't be used with image.filename");
        if (img_state(d) >= DICT_FILESCANNED)
            luaL_error(L, "image.stream is now read-only");
        if (img_pdfstream_ptr(d) == NULL)
            new_img_pdfstream_struct(d);
        xfree(img_pdfstream_stream(d));
        img_pdfstream_stream(d) = xstrdup(lua_tostring(L, -1));
        img_type(d) = IMG_TYPE_PDFSTREAM;
        break;
    case P_FILEPATH:
    case P_TOTALPAGES:
    case P_XSIZE:
    case P_YSIZE:
    case P_XRES:
    case P_YRES:
    case P_ROTATION:
    case P_IMAGETYPE:
    case P_OBJNUM:
    case P_INDEX:
    case P_COLORDEPTH:
        luaL_error(L, "image.%s is a read-only variable", img_parms[i].name);
        break;
    default:
        assert(0);
    }                           /* v k t ... */
}
Esempio n. 9
0
void GrimEngine::handleControls(int operation, int key, int /*keyModifier*/, uint16 ascii) {
	lua_Object buttonFunc, joyFunc;
	bool buttonFuncIsTable, joyFuncIsTable;

	// If we're not supposed to handle the key then don't
	if (!_controlsEnabled[key])
		return;

	lua_beginblock();

	lua_pushobject(lua_getref(refSystemTable));
	lua_pushstring("buttonHandler");
	lua_Object buttonHandler = lua_gettable();
	if (lua_istable(buttonHandler)) {
		lua_pushobject(buttonHandler);
		lua_pushstring("buttonHandler");
		buttonFunc = lua_gettable();
		if (!lua_isfunction(buttonFunc)) {
			error("handleControls: button handler not a function");
			return;
		}
		buttonFuncIsTable = true;
	} else if (lua_isfunction(buttonHandler)) {
		buttonFunc = buttonHandler;
		buttonFuncIsTable = false;
	} else {
		error("handleControls: invalid keys handler");
		return;
	}

	lua_pushobject(lua_getref(refSystemTable));
	lua_pushstring("axisHandler");
	lua_Object joyHandler = lua_gettable();
	if (lua_istable(joyHandler)) {
		lua_pushobject(joyHandler);
		lua_pushstring("axisHandler");
		joyFunc = lua_gettable();
		if (!lua_isfunction(joyFunc)) {
			error("handleControls: joystick handler not a function");
			return;
		}
		joyFuncIsTable = true;
	} else if (lua_isfunction(joyHandler)) {
		joyFunc = joyHandler;
		joyFuncIsTable = false;
	} else {
		error("handleControls: invalid joystick handler");
		return;
	}
	if (buttonFuncIsTable)
		lua_pushobject(buttonHandler);
	lua_pushnumber(key);
	if (operation == Common::EVENT_KEYDOWN) {
		lua_pushnumber(1);
		lua_pushnumber(1);
	} else {
		lua_pushnil();
		lua_pushnumber(0);
	}
	lua_pushnumber(0);
	lua_callfunction(buttonFunc);

	if (operation == Common::EVENT_KEYDOWN)
		_controlsState[key] = true;
	else if (operation == Common::EVENT_KEYUP)
		_controlsState[key] = false;

	lua_endblock();
}
Esempio n. 10
0
bool  LuaWrapper::isTable(int nIndex)						{	return lua_istable(m_luaState, nIndex);		}
Esempio n. 11
0
/* paths_setup
** Modify the lua path and cpath, prepending standard directories
** relative to this executable.
*/
static void paths_setup(lua_State *L, char *app) {
	char *temp, *binpath, *path;
	
	temp = malloc(PATH_MAX+1);
	if (!temp) {
		l_message("Error", "malloc failure for temp");
		exit(-1);
	}
	binpath = malloc(PATH_MAX+1);
	if (!binpath) {
		l_message("Error", "malloc failure for binpath");
		exit(-1);
	}
	path = malloc(PATH_MAX+1);
	if (!path) {
		l_message("Error", "malloc failure for path");
		exit(-1);
	}

	// full path to jive binary
	if (app[0] == '/') {
		// we were called with a full path
		strcpy(path, app);
	}
	else {
		// add working dir + app and resolve
		getcwd(temp, PATH_MAX+1);
		strcat(temp, "/");       
		strcat(temp, app);
		realpath(temp, path);
	}

	// directory containing jive
	strcpy(binpath, dirname(path));

	// set paths in lua (package.path & package cpath)
	lua_getglobal(L, "package");
	if (lua_istable(L, -1)) {
		luaL_Buffer b;
		luaL_buffinit(L, &b);

		// default lua path
		lua_getfield(L, -1, "path");
		luaL_addvalue(&b);
		luaL_addstring(&b, ";");

		// lua path relative to executable
#if !defined(WIN32)
		strcpy(temp, binpath);
		strcat(temp, "/../share/lua/5.1");
		realpath(temp, path);
#endif

		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?.lua;");
		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?" DIR_SEPARATOR_STR "?.lua;");

		// script path relative to executale
		strcpy(temp, binpath);
		strcat(temp, "/" LUA_DEFAULT_PATH);
		realpath(temp, path);

		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?.lua;");
		
		// set lua path
		luaL_pushresult(&b);
		lua_setfield(L, -2, "path");

		luaL_buffinit(L, &b);

		// default lua cpath
		lua_getfield(L, -1, "cpath");
		luaL_addvalue(&b);
		luaL_addstring(&b, ";");

		// lua cpath
#if !defined(WIN32)
		strcpy(temp, binpath);
		strcat(temp, "/../lib/lua/5.1");
		realpath(temp, path);
#endif

		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?." LIBRARY_EXT ";");
		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?" DIR_SEPARATOR_STR "core." LIBRARY_EXT ";");

		// cpath relative to executable
		strcpy(temp, binpath);
		strcat(temp, "/" LUA_DEFAULT_PATH);
		realpath(temp, path);

		luaL_addstring(&b, path);
		luaL_addstring(&b, DIR_SEPARATOR_STR "?." LIBRARY_EXT ";");

		// set lua cpath
		luaL_pushresult(&b);

		lua_setfield(L, -2, "cpath");
	}
	else {
		l_message("Error", "'package' is not a table");
	}

	// pop package table off the stack
	lua_pop(L, 1); 

	free(temp);
	free(binpath);
	free(path);
}
Esempio n. 12
0
static SoupCookie*
cookie_new_from_table(lua_State *L, gint idx, gchar **error)
{
    SoupCookie *cookie = NULL;
    SoupDate *date;
    const gchar *name, *value, *domain, *path;
    name = value = domain = path = NULL;
    gboolean secure, http_only;
    gint expires;

    /* correct relative index */
    if (idx < 0)
        idx = lua_gettop(L) + idx + 1;

    /* check for cookie table */
    if (!lua_istable(L, idx)) {
        *error = g_strdup_printf("invalid cookie table, got %s",
            lua_typename(L, lua_type(L, idx)));
        return NULL;
    }

#define IS_STRING  (lua_isstring(L, -1)  || lua_isnumber(L, -1))
#define IS_BOOLEAN (lua_isboolean(L, -1) || lua_isnil(L, -1))
#define IS_NUMBER  (lua_isnumber(L, -1))

#define GET_PROP(prop, typname, typexpr, typfunc)                           \
    lua_pushliteral(L, #prop);                                              \
    lua_rawget(L, idx);                                                     \
    if ((typexpr)) {                                                        \
        prop = typfunc(L, -1);                                              \
        lua_pop(L, 1);                                                      \
    } else {                                                                \
        *error = g_strdup_printf("invalid cookie." #prop " type, expected " \
            #typname ", got %s",  lua_typename(L, lua_type(L, -1)));        \
        return NULL;                                                        \
    }

    /* get cookie properties */
    GET_PROP(name,      string,  IS_STRING,  lua_tostring)
    GET_PROP(value,     string,  IS_STRING,  lua_tostring)
    GET_PROP(domain,    string,  IS_STRING,  lua_tostring)
    GET_PROP(path,      string,  IS_STRING,  lua_tostring)
    GET_PROP(secure,    boolean, IS_BOOLEAN, lua_toboolean)
    GET_PROP(http_only, boolean, IS_BOOLEAN, lua_toboolean)
    GET_PROP(expires,   number,  IS_NUMBER,  lua_tonumber)

#undef IS_STRING
#undef IS_BOOLEAN
#undef IS_NUMBER
#undef GET_PROP

    /* create soup cookie */
    if ((cookie = soup_cookie_new(name, value, domain, path, expires))) {
        soup_cookie_set_secure(cookie, secure);
        soup_cookie_set_http_only(cookie, http_only);

        /* set real expiry date from unixtime */
        if (expires > 0) {
            date = soup_date_new_from_time_t((time_t) expires);
            soup_cookie_set_expires(cookie, date);
            soup_date_free(date);
        }

        return cookie;
    }

    /* soup cookie creation failed */
    *error = g_strdup_printf("soup cookie creation failed");
    return NULL;
}
Esempio n. 13
0
/**
 * @brief Gets a planet.
 *
 * Possible values of param:
 *    - nil : -OBSOLETE- Gets the current landed planet or nil if there is none. Use planet.cur() instead.
 *    - bool : Gets a random planet.
 *    - faction : Gets random planet belonging to faction matching the number.
 *    - string : Gets the planet by name.
 *    - table : Gets random planet belonging to any of the factions in the
 *               table.
 *
 * @usage p,s = planet.get( "Anecu" ) -- Gets planet by name
 * @usage p,s = planet.get( faction.get( "Empire" ) ) -- Gets random Empire planet
 * @usage p,s = planet.get(true) -- Gets completely random planet
 * @usage p,s = planet.get( { faction.get("Empire"), faction.get("Dvaered") } ) -- Random planet belonging to Empire or Dvaered
 *    @luaparam param See description.
 *    @luareturn Returns the planet and the system it belongs to.
 * @luafunc get( param )
 */
static int planetL_get( lua_State *L )
{
   int i;
   int *factions;
   int nfactions;
   char **planets;
   int nplanets;
   const char *rndplanet;
   LuaPlanet planet;
   LuaSystem luasys;
   LuaFaction *f;
   Planet *pnt;
   StarSystem *sys;
   char *sysname;

   rndplanet = NULL;
   planets   = NULL;
   nplanets  = 0;

   /* Get the landed planet */
   if (lua_gettop(L) == 0) {
      if (land_planet != NULL) {
         planet.id = planet_index( land_planet );
         lua_pushplanet(L,planet);
         luasys.id = system_index( system_get( planet_getSystem(land_planet->name) ) );
         lua_pushsystem(L,luasys);
         return 2;
      }
      NLUA_ERROR(L,"Attempting to get landed planet when player not landed.");
      return 0; /* Not landed. */
   }

   /* If boolean return random. */
   else if (lua_isboolean(L,1)) {
      pnt = planet_get( space_getRndPlanet() );
      planet.id    = planet_index( pnt );
      lua_pushplanet(L,planet);
      luasys.id      = system_index( system_get( planet_getSystem(pnt->name) ) );
      lua_pushsystem(L,luasys);
      return 2;
   }

   /* Get a planet by faction */
   else if (lua_isfaction(L,1)) {
      f = lua_tofaction(L,1);
      planets = space_getFactionPlanet( &nplanets, &f->f, 1 );
   }

   /* Get a planet by name */
   else if (lua_isstring(L,1)) {
      rndplanet = lua_tostring(L,1);
   }

   /* Get a planet from faction list */
   else if (lua_istable(L,1)) {
      /* Get table length and preallocate. */
      nfactions = (int) lua_objlen(L,1);
      factions = malloc( sizeof(int) * nfactions );
      /* Load up the table. */
      lua_pushnil(L);
      i = 0;
      while (lua_next(L, -2) != 0) {
         f = lua_tofaction(L, -1);
         factions[i++] = f->f;
         lua_pop(L,1);
      }

      /* get the planets */
      planets = space_getFactionPlanet( &nplanets, factions, nfactions );
      free(factions);
   }
   else 
      NLUA_INVALID_PARAMETER(L); /* Bad Parameter */

   /* No suitable planet found */
   if ((rndplanet == NULL) && ((planets == NULL) || nplanets == 0))
      return 0;
   /* Pick random planet */
   else if (rndplanet == NULL) {
      rndplanet = planets[RNG(0,nplanets-1)];
      free(planets);
   }

   /* Push the planet */
   pnt = planet_get(rndplanet); /* The real planet */
   if (pnt == NULL) {
      NLUA_ERROR(L, "Planet '%s' not found in stack", rndplanet);
      return 0;
   }
   sysname = planet_getSystem(rndplanet);
   if (sysname == NULL) {
      NLUA_ERROR(L, "Planet '%s' is not placed in a system", rndplanet);
      return 0;
   }
   sys = system_get( sysname );
   if (sys == NULL) {
      NLUA_ERROR(L, "Planet '%s' can't find system '%s'", rndplanet, sysname); 
      return 0;
   }
   planet.id = planet_index( pnt );
   lua_pushplanet(L,planet);
   luasys.id = system_index( sys );
   lua_pushsystem(L,luasys);
   return 2;
}
Esempio n. 14
0
/*
** Returns a row of data from the query
** Lua Returns:
**   list of results or table of results depending on call
**   nil and error message otherwise.
*/
static int cur_fetch (lua_State *L) {
	ISC_STATUS fetch_stat;
	int i;
	cur_data *cur = getcursor(L,1);
	const char *opts = luaL_optstring (L, 3, "n");
	int num = strchr(opts, 'n') != NULL;
	int alpha = strchr(opts, 'a') != NULL;

	if ((fetch_stat = isc_dsql_fetch(cur->env->status_vector, &cur->stmt, 1, cur->out_sqlda)) == 0) {
		if (lua_istable (L, 2)) {
			/* remove the option string */
			lua_settop(L, 2);

			/* loop through the columns */
			for (i = 0; i < cur->out_sqlda->sqld; i++) {
				push_column(L, i, cur);

				if( num ) {
					lua_pushnumber(L, i+1);
					lua_pushvalue(L, -2);
					lua_settable(L, 2);
				}

				if( alpha ) {
					lua_pushlstring(L, cur->out_sqlda->sqlvar[i].aliasname, cur->out_sqlda->sqlvar[i].aliasname_length);
					lua_pushvalue(L, -2);
					lua_settable(L, 2);
				}

				lua_pop(L, 1);
			}

			/* returning given table */
			return 1;
		} else {
			for (i = 0; i < cur->out_sqlda->sqld; i++)
				push_column(L, i, cur);

			/* returning a list of values */
			return cur->out_sqlda->sqld;
		}
	}

	/* isc_dsql_fetch returns 100 if no more rows remain to be retrieved
	   so this can be ignored */
	if (fetch_stat != 100L)
		return return_db_error(L, cur->env->status_vector);

	/* last row has been fetched, close cursor */
	isc_dsql_free_statement(cur->env->status_vector, &cur->stmt, DSQL_drop);
	if ( CHECK_DB_ERROR(cur->env->status_vector) )
		return return_db_error(L, cur->env->status_vector);

	/* free the cursor data */
	free_cur(cur);

	cur->closed = 1;

	/* remove cursor from lock count */
	--cur->conn->lock;

	/* return sucsess */
	return 0;
}
Esempio n. 15
0
LUA_API int luafan_objectbuf_decode(lua_State *L)
{
  size_t len;
  const char *buf = luaL_checklstring(L, 1, &len);
  BYTEARRAY input;
  bytearray_wrap_buffer(&input, (uint8_t *)buf, len); // will not change buf.

  int sym_idx = 0;
  if (lua_istable(L, 2))
  {
    sym_idx = 2;
  }

  uint8_t flag = 0;
  bytearray_read8(&input, &flag);

  switch (flag)
  {
  case 0:
    lua_pushboolean(L, false);
    return 1;
  case 1:
    lua_pushboolean(L, true);
    return 1;
  default:
    break;
  }

  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_VK);
  }
  int sym_map_vk_idx = lua_gettop(L);

  int last_top = index + 1;

  if (!sym_idx)
  {
    lua_pushboolean(L, false);
    lua_rawseti(L, index_map_idx, FALSE_INDEX);
    lua_pushboolean(L, true);
    lua_rawseti(L, index_map_idx, TRUE_INDEX);
  }

  if (flag & HAS_NUMBER_MASK)
  {
    last_top = index + 1;
    uint32_t count = 0;
    if (!ffi_stream_get_u30(&input, &count))
    {
      lua_pushnil(L);
      lua_pushliteral(L, "decode failed, can't get `number` count.");
      return 2;
    }
    uint32_t i = 1;
    for (; i <= count; i++)
    {
      double result = 0;
      if (!ffi_stream_get_d64(&input, &result))
      {
        lua_pushnil(L);
        lua_pushfstring(L, "decode failed, can't decode `number`, %d/%d", i, count);
        return 2;
      }
      lua_pushnumber(L, result);
      lua_rawseti(L, index_map_idx, ++index);
    }
  }

  if (flag & HAS_U30_MASK)
  {
    last_top = index + 1;
    uint32_t count = 0;
    if (!ffi_stream_get_u30(&input, &count))
    {
      lua_pushnil(L);
      lua_pushliteral(L, "decode failed.");
      return 2;
    }
    uint32_t i = 1;
    for (; i <= count; i++)
    {
      uint32_t count = 0;
      if (!ffi_stream_get_u30(&input, &count))
      {
        lua_pushnil(L);
        lua_pushliteral(L, "decode failed.");
        return 2;
      }
      lua_pushinteger(L, count);
      lua_rawseti(L, index_map_idx, ++index);
    }
  }

  if (flag & HAS_STRING_MASK)
  {
    last_top = index + 1;
    uint32_t count = 0;
    if (!ffi_stream_get_u30(&input, &count))
    {
      lua_pushnil(L);
      lua_pushliteral(L, "decode failed.");
      return 2;
    }
    uint32_t i = 1;
    for (; i <= count; i++)
    {
      uint8_t *buff = NULL;
      size_t buflen = 0;
      ffi_stream_get_string(&input, &buff, &buflen);
      if (!buff)
      {
        lua_pushnil(L);
        lua_pushliteral(L, "decode failed.");
        return 2;
      }
      lua_pushlstring(L, (const char *)buff, buflen);
      lua_rawseti(L, index_map_idx, ++index);
    }
  }

  if (flag & HAS_TABLE_MASK)
  {
    last_top = index + 1;
    uint32_t count = 0;
    if (!ffi_stream_get_u30(&input, &count))
    {
      lua_pushnil(L);
      lua_pushliteral(L, "decode failed.");
      return 2;
    }
    uint32_t i = 1;
    for (; i <= count; i++)
    {
      lua_newtable(L);
      lua_rawseti(L, index_map_idx, index + i);
    }

    i = 1;
    for (; i <= count; i++)
    {
      uint8_t *buff = NULL;
      size_t buflen = 0;
      ffi_stream_get_string(&input, &buff, &buflen);
      if (!buff)
      {
        lua_pushnil(L);
        lua_pushliteral(L, "decode failed.");
        return 2;
      }
      BYTEARRAY d = {0};
      bytearray_wrap_buffer(&d, buff, buflen);

      lua_rawgeti(L, index_map_idx, index + i);
      while (bytearray_read_available(&d) > 0)
      {
        uint32_t ki = 0;
        if (!ffi_stream_get_u30(&d, &ki))
        {
          lua_pushnil(L);
          lua_pushliteral(L, "decode failed.");
          return 2;
        }
        uint32_t vi = 0;
        if (!ffi_stream_get_u30(&d, &vi))
        {
          lua_pushnil(L);
          lua_pushliteral(L, "decode failed.");
          return 2;
        }

        lua_rawgeti(L, sym_map_vk_idx, ki);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          lua_rawgeti(L, index_map_idx, ki);

          if (lua_isnil(L, -1))
          {
            luaL_error(L, "ki=%d not found.", ki);
          }
        }

        lua_rawgeti(L, sym_map_vk_idx, vi);
        if (lua_isnil(L, -1))
        {
          lua_pop(L, 1);
          lua_rawgeti(L, index_map_idx, vi);

          if (lua_isnil(L, -1))
          {
            luaL_error(L, "vi=%d not found.", vi);
          }
        }

        lua_rawset(L, -3);
      }
      lua_pop(L, 1);
    }
  }

  lua_rawgeti(L, sym_map_vk_idx, last_top);
  if (lua_isnil(L, -1))
  {
    lua_rawgeti(L, index_map_idx, last_top);
  }
  // return sym_map_vk[last_top] or index_map[last_top]
  // lua_pushvalue(L, index_map_idx);
  // lua_pushinteger(L, last_top);
  return 1;
}
Esempio n. 16
0
/**
**  Parse the action for spell.
**
**  @param l  Lua state.
*/
static SpellActionType *CclSpellAction(lua_State *l)
{
	const char *value;
	int args;
	int j;

	if (!lua_istable(l, -1)) {
		LuaError(l, "incorrect argument");
	}
	args = lua_objlen(l, -1);
	j = 0;

	lua_rawgeti(l, -1, j + 1);
	value = LuaToString(l, -1);
	lua_pop(l, 1);
	++j;

	if (!strcmp(value, "spawn-missile")) {
		SpawnMissile *spellaction = new SpawnMissile;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "damage")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Damage = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "delay")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Delay = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "ttl")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->TTL = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "start-point")) {
				lua_rawgeti(l, -1, j + 1);
				CclSpellMissileLocation(l, &spellaction->StartPoint);
				lua_pop(l, 1);
			} else if (!strcmp(value, "end-point")) {
				lua_rawgeti(l, -1, j + 1);
				CclSpellMissileLocation(l, &spellaction->EndPoint);
				lua_pop(l, 1);
			} else if (!strcmp(value, "missile")) {
				lua_rawgeti(l, -1, j + 1);
				value = LuaToString(l, -1);
				spellaction->Missile = MissileTypeByIdent(value);
				if (spellaction->Missile == NULL) {
					DebugPrint("in spawn-missile : missile %s does not exist\n" _C_ value);
				}
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported spawn-missile tag: %s" _C_ value);
			}
		}
		// Now, checking value.
		if (spellaction->Missile == NULL) {
			LuaError(l, "Use a missile for spawn-missile (with missile)");
		}
		return spellaction;
	} else if (!strcmp(value, "area-adjust-vitals")) {
		AreaAdjustVitals *spellaction = new AreaAdjustVitals;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "hit-points")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->HP = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "mana-points")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Mana = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported area-adjust-vitals tag: %s" _C_ value);
			}
		}
		return spellaction;
	} else if (!strcmp(value, "area-bombardment")) {
		AreaBombardment *spellaction = new AreaBombardment;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "fields")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Fields = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "shards")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Shards = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "damage")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Damage = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "start-offset-x")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->StartOffsetX = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "start-offset-y")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->StartOffsetY = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "missile")) {
				lua_rawgeti(l, -1, j + 1);
				value = LuaToString(l, -1);
				spellaction->Missile = MissileTypeByIdent(value);
				if (spellaction->Missile == NULL) {
					DebugPrint("in area-bombardement : missile %s does not exist\n" _C_ value);
				}
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported area-bombardment tag: %s" _C_ value);
			}
		}
		// Now, checking value.
		if (spellaction->Missile == NULL) {
			LuaError(l, "Use a missile for area-bombardment (with missile)");
		}
		return spellaction;
	} else if (!strcmp(value, "demolish")) {
		Demolish *spellaction = new Demolish;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "range")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Range = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "damage")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Damage = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported demolish tag: %s" _C_ value);
			}
		}
		return spellaction;
	} else if (!strcmp(value, "adjust-variable")) {
		AdjustVariable *spellaction = new AdjustVariable;
		lua_rawgeti(l, -1, j + 1);
		if (!lua_istable(l, -1)) {
			LuaError(l, "Table expected for adjust-variable.");
		}
		spellaction->Var = new SpellActionTypeAdjustVariable[UnitTypeVar.GetNumberVariable()];
		for (lua_pushnil(l); lua_next(l, -2); lua_pop(l, 1)) {
			const char *const name = LuaToString(l, -2);
			int i = UnitTypeVar.VariableNameLookup[name];

			if (i == -1) {
				LuaError(l, "in adjust-variable : Bad variable index : '%s'" _C_ LuaToString(l, -2));
			}
			if (lua_isnumber(l, -1)) {
				spellaction->Var[i].Enable = (LuaToNumber(l, -1) != 0);
				spellaction->Var[i].ModifEnable = 1;
				spellaction->Var[i].Value = LuaToNumber(l, -1);
				spellaction->Var[i].ModifValue = 1;
				spellaction->Var[i].Max = LuaToNumber(l, -1);
				spellaction->Var[i].ModifMax = 1;
			} else if (lua_istable(l, -1)) {
				for (lua_pushnil(l); lua_next(l, -2); lua_pop(l, 1)) {
					const char *const key = LuaToString(l, -2);
					if (!strcmp(key, "Enable")) {
						spellaction->Var[i].Enable = LuaToBoolean(l, -1);
						spellaction->Var[i].ModifEnable = 1;
					} else if (!strcmp(key, "Value")) {
						spellaction->Var[i].Value = LuaToNumber(l, -1);
						spellaction->Var[i].ModifValue = 1;
					} else if (!strcmp(key, "Max")) {
						spellaction->Var[i].Max = LuaToNumber(l, -1);
						spellaction->Var[i].ModifMax = 1;
					} else if (!strcmp(key, "Increase")) {
						spellaction->Var[i].Increase = LuaToNumber(l, -1);
						spellaction->Var[i].ModifIncrease = 1;
					} else if (!strcmp(key, "InvertEnable")) {
						spellaction->Var[i].InvertEnable = LuaToBoolean(l, -1);
					} else if (!strcmp(key, "AddValue")) {
						spellaction->Var[i].AddValue = LuaToNumber(l, -1);
					} else if (!strcmp(key, "AddMax")) {
						spellaction->Var[i].AddMax = LuaToNumber(l, -1);
					} else if (!strcmp(key, "AddIncrease")) {
						spellaction->Var[i].AddIncrease = LuaToNumber(l, -1);
					} else if (!strcmp(key, "IncreaseTime")) {
						spellaction->Var[i].IncreaseTime = LuaToNumber(l, -1);
					} else if (!strcmp(key, "TargetIsCaster")) {
						value = LuaToString(l, -1);
						if (!strcmp(value, "caster")) {
							spellaction->Var[i].TargetIsCaster = 1;
						} else if (!strcmp(value, "target")) {
							spellaction->Var[i].TargetIsCaster = 0;
						} else { // Error
							LuaError(l, "key '%s' not valid for TargetIsCaster in adjustvariable" _C_ value);
						}
					} else { // Error
						LuaError(l, "key '%s' not valid for adjustvariable" _C_ key);
					}
				}
			} else {
				LuaError(l, "in adjust-variable : Bad variable value");
			}
		}
		lua_pop(l, 1); // pop table
		return spellaction;
	} else if (!strcmp(value, "summon")) {
		Summon *spellaction = new Summon;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "unit-type")) {
				lua_rawgeti(l, -1, j + 1);
				value = LuaToString(l, -1);
				lua_pop(l, 1);
				spellaction->UnitType = UnitTypeByIdent(value);
				if (!spellaction->UnitType) {
					spellaction->UnitType = 0;
					DebugPrint("unit type \"%s\" not found for summon spell.\n" _C_ value);
				}
			} else if (!strcmp(value, "time-to-live")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->TTL = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "require-corpse")) {
				spellaction->RequireCorpse = 1;
				--j;
			} else {
				LuaError(l, "Unsupported summon tag: %s" _C_ value);
			}
		}
		// Now, checking value.
		if (spellaction->UnitType == NULL) {
			LuaError(l, "Use a unittype for summon (with unit-type)");
		}
		return spellaction;
	} else if (!strcmp(value, "spawn-portal")) {
		SpawnPortal *spellaction = new SpawnPortal;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "portal-type")) {
				lua_rawgeti(l, -1, j + 1);
				value = LuaToString(l, -1);
				lua_pop(l, 1);
				spellaction->PortalType = UnitTypeByIdent(value);
				if (!spellaction->PortalType) {
					spellaction->PortalType = 0;
					DebugPrint("unit type \"%s\" not found for spawn-portal.\n" _C_ value);
				}
			} else {
				LuaError(l, "Unsupported spawn-portal tag: %s" _C_ value);
			}
		}
		// Now, checking value.
		if (spellaction->PortalType == NULL) {
			LuaError(l, "Use a unittype for spawn-portal (with portal-type)");
		}
		return spellaction;
	} else if (!strcmp(value, "capture")) {
		Capture *spellaction = new Capture;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "sacrifice")) {
				spellaction->SacrificeEnable = 1;
			} else if (!strcmp(value, "damage")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Damage = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "percent")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->DamagePercent = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported Capture tag: %s" _C_ value);
			}
		}
		return spellaction;
	} else if (!strcmp(value, "polymorph")) {
		Polymorph *spellaction = new Polymorph;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "new-form")) {
				lua_rawgeti(l, -1, j + 1);
				value = LuaToString(l, -1);
				lua_pop(l, 1);
				spellaction->NewForm = UnitTypeByIdent(value);
				if (!spellaction->NewForm) {
					spellaction->NewForm= 0;
					DebugPrint("unit type \"%s\" not found for polymorph spell.\n" _C_ value);
				}
				// FIXME: temp polymorphs? hard to do.
			} else if (!strcmp(value, "player-neutral")) {
				spellaction->PlayerNeutral = 1;
				--j;
			} else {
				LuaError(l, "Unsupported polymorph tag: %s" _C_ value);
			}
		}
		// Now, checking value.
		if (spellaction->NewForm == NULL) {
			LuaError(l, "Use a unittype for polymorph (with new-form)");
		}
		return spellaction;
	} else if (!strcmp(value, "adjust-vitals")) {
		AdjustVitals *spellaction = new AdjustVitals;
		for (; j < args; ++j) {
			lua_rawgeti(l, -1, j + 1);
			value = LuaToString(l, -1);
			lua_pop(l, 1);
			++j;
			if (!strcmp(value, "hit-points")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->HP = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "mana-points")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->Mana = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else if (!strcmp(value, "max-multi-cast")) {
				lua_rawgeti(l, -1, j + 1);
				spellaction->MaxMultiCast = LuaToNumber(l, -1);
				lua_pop(l, 1);
			} else {
				LuaError(l, "Unsupported adjust-vitals tag: %s" _C_ value);
			}
		}
		return spellaction;
	} else {
		LuaError(l, "Unsupported action type: %s" _C_ value);
	}
	return NULL;
}
Esempio n. 17
0
 bool Environment::isTable(int index) {
     return lua_istable(L, index);
 }
Esempio n. 18
0
/**
**  Parse the Condition for spell.
**
**  @param l          Lua state.
**  @param condition  pointer to condition to fill with data.
**
**  @note Conditions must be allocated. All data already in is LOST.
*/
static void CclSpellCondition(lua_State *l, ConditionInfo *condition)
{
	const char *value;
	unsigned int i;
	int args;
	int j;

	//
	// Initializations:
	//

	// Flags are defaulted to 0(CONDITION_TRUE)
	size_t new_bool_size = UnitTypeVar.GetNumberBoolFlag();

	condition->BoolFlag = new char[new_bool_size];
	memset(condition->BoolFlag, 0, new_bool_size * sizeof(char));

	condition->Variable = new ConditionInfoVariable[UnitTypeVar.GetNumberVariable()];
	// Initialize min/max stuff to values with no effect.
	for (i = 0; i < UnitTypeVar.GetNumberVariable(); i++) {
		condition->Variable[i].MinValue = -1;
		condition->Variable[i].MaxValue = -1;
		condition->Variable[i].MinMax = -1;
		condition->Variable[i].MinValuePercent = -8;
		condition->Variable[i].MaxValuePercent = 1024;
	}
	//  Now parse the list and set values.
	if (!lua_istable(l, -1)) {
		LuaError(l, "incorrect argument");
	}
	args = lua_objlen(l, -1);
	for (j = 0; j < args; ++j) {
		lua_rawgeti(l, -1, j + 1);
		value = LuaToString(l, -1);
		lua_pop(l, 1);
		++j;
		if (!strcmp(value, "alliance")) {
			lua_rawgeti(l, -1, j + 1);
			condition->Alliance = Ccl2Condition(l, LuaToString(l, -1));
			lua_pop(l, 1);
		} else if (!strcmp(value, "opponent")) {
			lua_rawgeti(l, -1, j + 1);
			condition->Opponent = Ccl2Condition(l, LuaToString(l, -1));
			lua_pop(l, 1);
		} else if (!strcmp(value, "self")) {
			lua_rawgeti(l, -1, j + 1);
			condition->TargetSelf = Ccl2Condition(l, LuaToString(l, -1));
			lua_pop(l, 1);
		} else {
			int index = UnitTypeVar.BoolFlagNameLookup[value];
			if (index != -1) {
				lua_rawgeti(l, -1, j + 1);
				condition->BoolFlag[index] = Ccl2Condition(l, LuaToString(l, -1));
				lua_pop(l, 1);
				continue;
			}
			index = UnitTypeVar.VariableNameLookup[value];
			if (index != -1) { // Valid index.
				lua_rawgeti(l, -1, j + 1);
				if (!lua_istable(l, -1)) {
					LuaError(l, "Table expected in variable in condition");
				}
				for (lua_pushnil(l); lua_next(l, -2); lua_pop(l, 1)) {
					const char *const key = LuaToString(l, -2);
					if (!strcmp(key, "Enable")) {
						condition->Variable[index].Enable = Ccl2Condition(l, LuaToString(l, -1));
					} else if (!strcmp(key, "MinValue")) {
						condition->Variable[index].MinValue = LuaToNumber(l, -1);
					} else if (!strcmp(key, "MaxValue")) {
						condition->Variable[index].MaxValue = LuaToNumber(l, -1);
					} else if (!strcmp(key, "MinMax")) {
						condition->Variable[index].MinMax = LuaToNumber(l, -1);
					} else if (!strcmp(key, "MinValuePercent")) {
						condition->Variable[index].MinValuePercent = LuaToNumber(l, -1);
					} else if (!strcmp(key, "MaxValuePercent")) {
						condition->Variable[index].MaxValuePercent = LuaToNumber(l, -1);
					} else if (!strcmp(key, "ConditionApplyOnCaster")) {
						condition->Variable[index].ConditionApplyOnCaster = LuaToBoolean(l, -1);
					} else { // Error
						LuaError(l, "%s invalid for Variable in condition" _C_ key);
					}
				}
				lua_pop(l, 1); // lua_rawgeti()
				continue;
			}
			LuaError(l, "Unsuported condition tag: %s" _C_ value);
		}
	}
}
Esempio n. 19
0
int plugin_debug_con_handle_stmt(chassis *chas, network_mysqld_con *con, GString *s) {
	gsize i, j;
	GPtrArray *fields;
	GPtrArray *rows;
	GPtrArray *row;

	switch(s->str[NET_HEADER_SIZE]) {
	case COM_QUERY:
		fields = NULL;
		rows = NULL;
		row = NULL;

		/* support the basic commands sent by the mysql shell */
		if (0 == g_ascii_strncasecmp(s->str + NET_HEADER_SIZE + 1, C("select @@version_comment limit 1"))) {
			MYSQL_FIELD *field;

			fields = network_mysqld_proto_fielddefs_new();

			field = network_mysqld_proto_fielddef_new();
			field->name = g_strdup("@@version_comment");
			field->type = FIELD_TYPE_VAR_STRING;
			g_ptr_array_add(fields, field);

			rows = g_ptr_array_new();
			row = g_ptr_array_new();
			g_ptr_array_add(row, g_strdup("MySQL Enterprise Agent"));
			g_ptr_array_add(rows, row);

			network_mysqld_con_send_resultset(con->client, fields, rows);
			
		} else if (0 == g_ascii_strncasecmp(s->str + NET_HEADER_SIZE + 1, C("select USER()"))) {
			MYSQL_FIELD *field;

			fields = network_mysqld_proto_fielddefs_new();
			field = network_mysqld_proto_fielddef_new();
			field->name = g_strdup("USER()");
			field->type = FIELD_TYPE_VAR_STRING;
			g_ptr_array_add(fields, field);

			rows = g_ptr_array_new();
			row = g_ptr_array_new();
			g_ptr_array_add(row, g_strdup("root"));
			g_ptr_array_add(rows, row);

			network_mysqld_con_send_resultset(con->client, fields, rows);
		} else {
			MYSQL_FIELD *field = NULL;
			lua_State *L = chas->sc->L;

			if (0 == luaL_loadstring(L, s->str + NET_HEADER_SIZE + 1) &&
			    0 == lua_pcall(L, 0, 1, 0)) {
				/* let's see what is on the stack
				 * - scalars are turned into strings
				 *   return "foo" 
				 * - 1-dim tables are turned into a single-row result-set
				 *   return { foo = "bar", baz = "foz" }
				 * - 2-dim tables are turned into a multi-row result-set
				 *   return { { foo = "bar" }, { "foz" } }
				 */
				switch (lua_type(L, -1)) {
				case LUA_TTABLE:
					/* take the names from the fields */
					fields = network_mysqld_proto_fielddefs_new();

					lua_pushnil(L);
					while (lua_next(L, -2) != 0) {
						if (lua_istable(L, -1)) {
							/* 2-dim table
							 * 
							 * we only only take the keys from the first row
							 * afterwards we ignore them
							 */
					
							lua_pushnil(L);
							while (lua_next(L, -2) != 0) {
								if (!rows) {
									/* this is the 1st round, add the keys */
									lua_table_key_to_mysql_field(L, fields);
								}

								if (!row) row = g_ptr_array_new();
								if (lua_isboolean(L, -1)) {
									g_ptr_array_add(row, g_strdup(lua_toboolean(L, -1) ? "TRUE" : "FALSE"));
								} else if (lua_isnumber(L, -1)) {
									g_ptr_array_add(row, g_strdup_printf("%.0f", lua_tonumber(L, -1)));
								} else {
									g_ptr_array_add(row, g_strdup(lua_tostring(L, -1)));
								}

								lua_pop(L, 1); /* pop the value, but keep the key on the stack */
							}
					
							if (!rows) rows = g_ptr_array_new();
							g_ptr_array_add(rows, row);

							row = NULL;
						} else {
							/* 1-dim table */
							lua_table_key_to_mysql_field(L, fields);

							if (!row) row = g_ptr_array_new();
							if (lua_isboolean(L, -1)) {
								g_ptr_array_add(row, g_strdup(lua_toboolean(L, -1) ? "TRUE" : "FALSE"));
							} else if (lua_isnumber(L, -1)) {
								g_ptr_array_add(row, g_strdup_printf("%.0f", lua_tonumber(L, -1)));
							} else {
								g_ptr_array_add(row, g_strdup(lua_tostring(L, -1)));
							}
						}

						lua_pop(L, 1); /* pop the value, but keep the key on the stack */
					}

					if (row) {
						/* in 1-dim we have to append the row to the result-set,
						 * in 2-dim this is already done and row is NULL */
						if (!rows) rows = g_ptr_array_new();
						g_ptr_array_add(rows, row);
					}

					break;
				default:
					/* a scalar value */
					fields = network_mysqld_proto_fielddefs_new();
					field = network_mysqld_proto_fielddef_new();
					field->name = g_strdup("lua");
					field->type = FIELD_TYPE_VAR_STRING;
					g_ptr_array_add(fields, field);
		
					rows = g_ptr_array_new();
					row = g_ptr_array_new();
					g_ptr_array_add(row, g_strdup(lua_tostring(L, -1)));
					g_ptr_array_add(rows, row);

					break;
				}

				lua_pop(L, 1); /* get rid of the result */

				network_mysqld_con_send_resultset(con->client, fields, rows);
			}

			/* if we don't have fields for the resultset, we should have a
			 * error-msg on the stack */
			if (!fields) {
				size_t err_len = 0;
				const char *err;

				err = lua_tolstring(L, -1, &err_len);

				network_mysqld_con_send_error(con->client, err, err_len);
				
				lua_pop(L, 1);
			}
		}

		/* clean up */
		if (fields) {
			network_mysqld_proto_fielddefs_free(fields);
			fields = NULL;
		}

		if (rows) {
			for (i = 0; i < rows->len; i++) {
				row = rows->pdata[i];

				for (j = 0; j < row->len; j++) {
					g_free(row->pdata[j]);
				}

				g_ptr_array_free(row, TRUE);
			}
			g_ptr_array_free(rows, TRUE);
			rows = NULL;
		}

		break;
	case COM_QUIT:
		break;
	case COM_INIT_DB:
		network_mysqld_con_send_ok(con->client);
		break;
	default:
		network_mysqld_con_send_error(con->client, C("unknown COM_*"));
		break;
	}

	return 0;
}
Esempio n. 20
0
/**
**  Parse Spell.
**
**  @param l  Lua state.
*/
static int CclDefineSpell(lua_State *l)
{
	std::string identname;
	SpellType *spell;
	const char *value;
	int args;
	int i;

	args = lua_gettop(l);
	identname = LuaToString(l, 1);
	spell = SpellTypeByIdent(identname);
	if (spell != NULL) {
		DebugPrint("Redefining spell-type `%s'\n" _C_ identname.c_str());
	} else {
		spell = new SpellType(SpellTypeTable.size(), identname);
		for (std::vector<CUnitType *>::size_type i = 0; i < UnitTypes.size(); ++i) { // adjust array for caster already defined
			if (UnitTypes[i]->CanCastSpell) {
				char *newc = new char[(SpellTypeTable.size() + 1) * sizeof(char)];
				memcpy(newc, UnitTypes[i]->CanCastSpell, SpellTypeTable.size() * sizeof(char));
				delete[] UnitTypes[i]->CanCastSpell;
				UnitTypes[i]->CanCastSpell = newc;
				UnitTypes[i]->CanCastSpell[SpellTypeTable.size()] = 0;
			}
			if (UnitTypes[i]->AutoCastActive) {
				char *newc = new char[(SpellTypeTable.size() + 1) * sizeof(char)];
				memcpy(newc, UnitTypes[i]->AutoCastActive, SpellTypeTable.size() * sizeof(char));
				delete[] UnitTypes[i]->AutoCastActive;
				UnitTypes[i]->AutoCastActive = newc;
				UnitTypes[i]->AutoCastActive[SpellTypeTable.size()] = 0;
			}
		}
		SpellTypeTable.push_back(spell);
	}
	for (i = 1; i < args; ++i) {
		value = LuaToString(l, i + 1);
		++i;
		if (!strcmp(value, "showname")) {
			spell->Name = LuaToString(l, i + 1);
		} else if (!strcmp(value, "manacost")) {
			spell->ManaCost = LuaToNumber(l, i + 1);
		} else if (!strcmp(value, "range")) {
			if (!lua_isstring(l, i + 1) && !lua_isnumber(l, i + 1)) {
				LuaError(l, "incorrect argument");
			}
			if (lua_isstring(l, i + 1) && !strcmp(lua_tostring(l, i + 1), "infinite")) {
				spell->Range = INFINITE_RANGE;
			} else if (lua_isnumber(l, i + 1)) {
				spell->Range = static_cast<int>(lua_tonumber(l, i + 1));
			} else {
				LuaError(l, "Invalid range");
			}
		} else if (!strcmp(value, "repeat-cast")) {
			spell->RepeatCast = 1;
			--i;
		} else if (!strcmp(value, "target")) {
			value = LuaToString(l, i + 1);
			if (!strcmp(value, "self")) {
				spell->Target = TargetSelf;
			} else if (!strcmp(value, "unit")) {
				spell->Target = TargetUnit;
			} else if (!strcmp(value, "position")) {
				spell->Target = TargetPosition;
			} else {
				LuaError(l, "Unsupported spell target type tag: %s" _C_ value);
			}
		} else if (!strcmp(value, "action")) {
			int subargs;
			int k;

			if (!lua_istable(l, i + 1)) {
				LuaError(l, "incorrect argument");
			}
			subargs = lua_objlen(l, i + 1);
			for (k = 0; k < subargs; ++k) {
				lua_rawgeti(l, i + 1, k + 1);
				spell->Action.push_back(CclSpellAction(l));
				lua_pop(l, 1);
			}
		} else if (!strcmp(value, "condition")) {
			if (!spell->Condition) {
				spell->Condition = new ConditionInfo;
			}
			lua_pushvalue(l, i + 1);
			CclSpellCondition(l, spell->Condition);
			lua_pop(l, 1);
		} else if (!strcmp(value, "autocast")) {
			if (!spell->AutoCast) {
				spell->AutoCast = new AutoCastInfo();
			}
			lua_pushvalue(l, i + 1);
			CclSpellAutocast(l, spell->AutoCast);
			lua_pop(l, 1);
		} else if (!strcmp(value, "ai-cast")) {
			if (!spell->AICast) {
				spell->AICast = new AutoCastInfo();
			}
			lua_pushvalue(l, i + 1);
			CclSpellAutocast(l, spell->AICast);
			lua_pop(l, 1);
		} else if (!strcmp(value, "sound-when-cast")) {
			//  Free the old name, get the new one
			spell->SoundWhenCast.Name = LuaToString(l, i + 1);
			spell->SoundWhenCast.Sound = SoundForName(spell->SoundWhenCast.Name);
			//  Check for sound.
			if (!spell->SoundWhenCast.Sound) {
				spell->SoundWhenCast.Name.clear();
			}
		} else if (!strcmp(value, "depend-upgrade")) {
			value = LuaToString(l, i + 1);
			spell->DependencyId = UpgradeIdByIdent(value);
			if (spell->DependencyId == -1) {
				lua_pushfstring(l, "Bad upgrade name: %s", value);
			}
		} else {
			LuaError(l, "Unsupported tag: %s" _C_ value);
		}
	}
	return 0;
}
Esempio n. 21
0
static int player_get(lua_State *L)
{
	player_t *plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER));
	const char *field = luaL_checkstring(L, 2);

	if (!plr) {
		if (fastcmp(field,"valid")) {
			lua_pushboolean(L, false);
			return 1;
		}
		return LUA_ErrInvalid(L, "player_t");
	}

	if (fastcmp(field,"valid"))
		lua_pushboolean(L, true);
	else if (fastcmp(field,"name"))
		lua_pushstring(L, player_names[plr-players]);
	else if (fastcmp(field,"mo"))
	{
		if (plr->spectator)
			lua_pushnil(L);
		else
			LUA_PushUserdata(L, plr->mo, META_MOBJ);
	}
	else if (fastcmp(field,"cmd"))
		LUA_PushUserdata(L, &plr->cmd, META_TICCMD);
	else if (fastcmp(field,"playerstate"))
		lua_pushinteger(L, plr->playerstate);
	else if (fastcmp(field,"viewz"))
		lua_pushfixed(L, plr->viewz);
	else if (fastcmp(field,"viewheight"))
		lua_pushfixed(L, plr->viewheight);
	else if (fastcmp(field,"deltaviewheight"))
		lua_pushfixed(L, plr->deltaviewheight);
	else if (fastcmp(field,"bob"))
		lua_pushfixed(L, plr->bob);
	else if (fastcmp(field,"aiming"))
		lua_pushangle(L, plr->aiming);
	else if (fastcmp(field,"health"))
		lua_pushinteger(L, plr->health);
	else if (fastcmp(field,"pity"))
		lua_pushinteger(L, plr->pity);
	else if (fastcmp(field,"currentweapon"))
		lua_pushinteger(L, plr->currentweapon);
	else if (fastcmp(field,"ringweapons"))
		lua_pushinteger(L, plr->ringweapons);
	else if (fastcmp(field,"powers"))
		LUA_PushUserdata(L, plr->powers, META_POWERS);
	else if (fastcmp(field,"pflags"))
		lua_pushinteger(L, plr->pflags);
	else if (fastcmp(field,"panim"))
		lua_pushinteger(L, plr->panim);
	else if (fastcmp(field,"flashcount"))
		lua_pushinteger(L, plr->flashcount);
	else if (fastcmp(field,"flashpal"))
		lua_pushinteger(L, plr->flashpal);
	else if (fastcmp(field,"skincolor"))
		lua_pushinteger(L, plr->skincolor);
	else if (fastcmp(field,"score"))
		lua_pushinteger(L, plr->score);
	else if (fastcmp(field,"dashspeed"))
		lua_pushfixed(L, plr->dashspeed);
	else if (fastcmp(field,"dashtime"))
		lua_pushinteger(L, plr->dashtime);
	else if (fastcmp(field,"normalspeed"))
		lua_pushfixed(L, plr->normalspeed);
	else if (fastcmp(field,"runspeed"))
		lua_pushfixed(L, plr->runspeed);
	else if (fastcmp(field,"thrustfactor"))
		lua_pushinteger(L, plr->thrustfactor);
	else if (fastcmp(field,"accelstart"))
		lua_pushinteger(L, plr->accelstart);
	else if (fastcmp(field,"acceleration"))
		lua_pushinteger(L, plr->acceleration);
	else if (fastcmp(field,"charability"))
		lua_pushinteger(L, plr->charability);
	else if (fastcmp(field,"charability2"))
		lua_pushinteger(L, plr->charability2);
	else if (fastcmp(field,"charflags"))
		lua_pushinteger(L, plr->charflags);
	else if (fastcmp(field,"thokitem"))
		lua_pushinteger(L, plr->thokitem);
	else if (fastcmp(field,"spinitem"))
		lua_pushinteger(L, plr->spinitem);
	else if (fastcmp(field,"revitem"))
		lua_pushinteger(L, plr->revitem);
	else if (fastcmp(field,"actionspd"))
		lua_pushfixed(L, plr->actionspd);
	else if (fastcmp(field,"mindash"))
		lua_pushfixed(L, plr->mindash);
	else if (fastcmp(field,"maxdash"))
		lua_pushfixed(L, plr->maxdash);
	else if (fastcmp(field,"jumpfactor"))
		lua_pushfixed(L, plr->jumpfactor);
	else if (fastcmp(field,"lives"))
		lua_pushinteger(L, plr->lives);
	else if (fastcmp(field,"continues"))
		lua_pushinteger(L, plr->continues);
	else if (fastcmp(field,"xtralife"))
		lua_pushinteger(L, plr->xtralife);
	else if (fastcmp(field,"gotcontinue"))
		lua_pushinteger(L, plr->gotcontinue);
	else if (fastcmp(field,"speed"))
		lua_pushfixed(L, plr->speed);
	else if (fastcmp(field,"jumping"))
		lua_pushboolean(L, plr->jumping);
	else if (fastcmp(field,"secondjump"))
		lua_pushinteger(L, plr->secondjump);
	else if (fastcmp(field,"fly1"))
		lua_pushinteger(L, plr->fly1);
	else if (fastcmp(field,"scoreadd"))
		lua_pushinteger(L, plr->scoreadd);
	else if (fastcmp(field,"glidetime"))
		lua_pushinteger(L, plr->glidetime);
	else if (fastcmp(field,"climbing"))
		lua_pushinteger(L, plr->climbing);
	else if (fastcmp(field,"deadtimer"))
		lua_pushinteger(L, plr->deadtimer);
	else if (fastcmp(field,"exiting"))
		lua_pushinteger(L, plr->exiting);
	else if (fastcmp(field,"homing"))
		lua_pushinteger(L, plr->homing);
	else if (fastcmp(field,"skidtime"))
		lua_pushinteger(L, plr->skidtime);
	else if (fastcmp(field,"cmomx"))
		lua_pushfixed(L, plr->cmomx);
	else if (fastcmp(field,"cmomy"))
		lua_pushfixed(L, plr->cmomy);
	else if (fastcmp(field,"rmomx"))
		lua_pushfixed(L, plr->rmomx);
	else if (fastcmp(field,"rmomy"))
		lua_pushfixed(L, plr->rmomy);
	else if (fastcmp(field,"numboxes"))
		lua_pushinteger(L, plr->numboxes);
	else if (fastcmp(field,"totalring"))
		lua_pushinteger(L, plr->totalring);
	else if (fastcmp(field,"realtime"))
		lua_pushinteger(L, plr->realtime);
	else if (fastcmp(field,"laps"))
		lua_pushinteger(L, plr->laps);
	else if (fastcmp(field,"ctfteam"))
		lua_pushinteger(L, plr->ctfteam);
	else if (fastcmp(field,"gotflag"))
		lua_pushinteger(L, plr->gotflag);
	else if (fastcmp(field,"weapondelay"))
		lua_pushinteger(L, plr->weapondelay);
	else if (fastcmp(field,"tossdelay"))
		lua_pushinteger(L, plr->tossdelay);
	else if (fastcmp(field,"starpostx"))
		lua_pushinteger(L, plr->starpostx);
	else if (fastcmp(field,"starposty"))
		lua_pushinteger(L, plr->starposty);
	else if (fastcmp(field,"starpostz"))
		lua_pushinteger(L, plr->starpostz);
	else if (fastcmp(field,"starpostnum"))
		lua_pushinteger(L, plr->starpostnum);
	else if (fastcmp(field,"starposttime"))
		lua_pushinteger(L, plr->starposttime);
	else if (fastcmp(field,"starpostangle"))
		lua_pushangle(L, plr->starpostangle);
	else if (fastcmp(field,"angle_pos"))
		lua_pushangle(L, plr->angle_pos);
	else if (fastcmp(field,"old_angle_pos"))
		lua_pushangle(L, plr->old_angle_pos);
	else if (fastcmp(field,"axis1"))
		LUA_PushUserdata(L, plr->axis1, META_MOBJ);
	else if (fastcmp(field,"axis2"))
		LUA_PushUserdata(L, plr->axis2, META_MOBJ);
	else if (fastcmp(field,"bumpertime"))
		lua_pushinteger(L, plr->bumpertime);
	else if (fastcmp(field,"flyangle"))
		lua_pushinteger(L, plr->flyangle);
	else if (fastcmp(field,"drilltimer"))
		lua_pushinteger(L, plr->drilltimer);
	else if (fastcmp(field,"linkcount"))
		lua_pushinteger(L, plr->linkcount);
	else if (fastcmp(field,"linktimer"))
		lua_pushinteger(L, plr->linktimer);
	else if (fastcmp(field,"anotherflyangle"))
		lua_pushinteger(L, plr->anotherflyangle);
	else if (fastcmp(field,"nightstime"))
		lua_pushinteger(L, plr->nightstime);
	else if (fastcmp(field,"drillmeter"))
		lua_pushinteger(L, plr->drillmeter);
	else if (fastcmp(field,"drilldelay"))
		lua_pushinteger(L, plr->drilldelay);
	else if (fastcmp(field,"bonustime"))
		lua_pushboolean(L, plr->bonustime);
	else if (fastcmp(field,"capsule"))
		LUA_PushUserdata(L, plr->capsule, META_MOBJ);
	else if (fastcmp(field,"mare"))
		lua_pushinteger(L, plr->mare);
	else if (fastcmp(field,"marebegunat"))
		lua_pushinteger(L, plr->marebegunat);
	else if (fastcmp(field,"startedtime"))
		lua_pushinteger(L, plr->startedtime);
	else if (fastcmp(field,"finishedtime"))
		lua_pushinteger(L, plr->finishedtime);
	else if (fastcmp(field,"finishedrings"))
		lua_pushinteger(L, plr->finishedrings);
	else if (fastcmp(field,"marescore"))
		lua_pushinteger(L, plr->marescore);
	else if (fastcmp(field,"lastmarescore"))
		lua_pushinteger(L, plr->lastmarescore);
	else if (fastcmp(field,"lastmare"))
		lua_pushinteger(L, plr->lastmare);
	else if (fastcmp(field,"maxlink"))
		lua_pushinteger(L, plr->maxlink);
	else if (fastcmp(field,"texttimer"))
		lua_pushinteger(L, plr->texttimer);
	else if (fastcmp(field,"textvar"))
		lua_pushinteger(L, plr->textvar);
	else if (fastcmp(field,"lastsidehit"))
		lua_pushinteger(L, plr->lastsidehit);
	else if (fastcmp(field,"lastlinehit"))
		lua_pushinteger(L, plr->lastlinehit);
	else if (fastcmp(field,"losstime"))
		lua_pushinteger(L, plr->losstime);
	else if (fastcmp(field,"timeshit"))
		lua_pushinteger(L, plr->timeshit);
	else if (fastcmp(field,"onconveyor"))
		lua_pushinteger(L, plr->onconveyor);
	else if (fastcmp(field,"awayviewmobj"))
		LUA_PushUserdata(L, plr->awayviewmobj, META_MOBJ);
	else if (fastcmp(field,"awayviewtics"))
		lua_pushinteger(L, plr->awayviewtics);
	else if (fastcmp(field,"awayviewaiming"))
		lua_pushangle(L, plr->awayviewaiming);
	else if (fastcmp(field,"spectator"))
		lua_pushboolean(L, plr->spectator);
	else if (fastcmp(field,"bot"))
		lua_pushinteger(L, plr->bot);
	else if (fastcmp(field,"jointime"))
		lua_pushinteger(L, plr->jointime);
#ifdef HWRENDER
	else if (fastcmp(field,"fovadd"))
		lua_pushfixed(L, plr->fovadd);
#endif
	else {
		lua_getfield(L, LUA_REGISTRYINDEX, LREG_EXTVARS);
		I_Assert(lua_istable(L, -1));
		lua_pushlightuserdata(L, plr);
		lua_rawget(L, -2);
		if (!lua_istable(L, -1)) { // no extra values table
			CONS_Debug(DBG_LUA, M_GetText("'%s' has no extvars table or field named '%s'; returning nil.\n"), "player_t", field);
			return 0;
		}
		lua_getfield(L, -1, field);
		if (lua_isnil(L, -1)) // no value for this field
			CONS_Debug(DBG_LUA, M_GetText("'%s' has no field named '%s'; returning nil.\n"), "player_t", field);
	}

	return 1;
}
Esempio n. 22
0
	bool TileType::loadStandardTileTypesLua(const char *filename)
	{
		LuaState lua(false);
		if (!lua.loadFile(filename))
		{
			lua.logStack("TITLE");
			lua.close();
			stringstream errss;
			errss << "Unable to load standard tile types";
			am_log("TILE", errss);
			return false;
		}

		lua_getglobal(lua, "types");
		if (!lua_istable(lua, -1))
		{
			stringstream errss;
			errss << "Unable to load standard tile types, loaded file was of type: " << lua_typename(lua, -1);
			am_log("TILE", errss);
			lua.close();
			return false;
		}

		/* table is in the stack at index 't' */
		lua_pushnil(lua);  /* first key */
		while (lua_next(lua, -2) != 0) 
		{
			/* uses 'key' (at index -2) and 'value' (at index -1) */
			if (lua_isstring(lua, -2))
			{
				if (!lua_istable(lua, -1))
				{
					stringstream errss;
					errss << "Tile type '" << lua_tostring(lua, -2) << "' was of type '" << lua_typename(lua, -1) << "' and not an object.";
					am_log("TILE", errss);
					continue;
				}

				string tileName = Utils::toLowerCase(lua_tostring(lua, -2));

				TileType *loadedType = new TileType(tileName.c_str());
				if (!loadedType->loadFromDef(lua))
				{
					stringstream errss;
					errss << "Failed to load '" << tileName << "' object in definition was invalid.";
					am_log("TILE", errss);
					delete loadedType;
					continue;
				}

				stringstream ss;
				ss << "Added tile type '" << loadedType->getName() << "'";
				am_log("TILE", ss);
				// TODO: Change to not needing this loadStandard function.
				Engine::getEngine()->addTileType(loadedType);
			}
			/* removes 'value'; keeps 'key' for next iteration */
			lua_pop(lua, 1);
		}
		lua.close();
		return true;
	}
Esempio n. 23
0
// hud_add(self, form)
int ObjectRef::l_hud_add(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	ObjectRef *ref = checkobject(L, 1);
	RemotePlayer *player = getplayer(ref);
	if (player == NULL)
		return 0;

	HudElement *elem = new HudElement;

	elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type",
								es_HudElementType, HUD_ELEM_TEXT);

	lua_getfield(L, 2, "position");
	elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
	lua_pop(L, 1);

	lua_getfield(L, 2, "scale");
	elem->scale = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
	lua_pop(L, 1);

	lua_getfield(L, 2, "size");
	elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32();
	lua_pop(L, 1);

	elem->name   = getstringfield_default(L, 2, "name", "");
	elem->text   = getstringfield_default(L, 2, "text", "");
	elem->number = getintfield_default(L, 2, "number", 0);
	elem->item   = getintfield_default(L, 2, "item", 0);
	elem->dir    = getintfield_default(L, 2, "direction", 0);

	// Deprecated, only for compatibility's sake
	if (elem->dir == 0)
		elem->dir = getintfield_default(L, 2, "dir", 0);

	lua_getfield(L, 2, "alignment");
	elem->align = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
	lua_pop(L, 1);

	lua_getfield(L, 2, "offset");
	elem->offset = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
	lua_pop(L, 1);

	lua_getfield(L, 2, "world_pos");
	elem->world_pos = lua_istable(L, -1) ? read_v3f(L, -1) : v3f();
	lua_pop(L, 1);

	/* check for known deprecated element usage */
	if ((elem->type  == HUD_ELEM_STATBAR) && (elem->size == v2s32())) {
		log_deprecated(L,"Deprecated usage of statbar without size!");
	}

	u32 id = getServer(L)->hudAdd(player, elem);
	if (id == U32_MAX) {
		delete elem;
		return 0;
	}

	lua_pushnumber(L, id);
	return 1;
}
Esempio n. 24
0
int LuaUtils_Introduce(lua_State *L)
{
  int n = LuaUtils_CheckParameter2(L, 1, 2, LuaUtils_IntroduceUsage);
  if (!lua_istable(L, 1))
    return LuaUtils_Error(L, "Not a table");

  if (n >= 2) {

    bool found = false;
    lua_pushstring(L, "__intrinsic");
    lua_gettable(L, -3);

    if (lua_islightuserdata(L, -1)) {

      const RegisterItem *items = lua_touserdata(L, -1);
      const char *library = items[0].name;
      const char *function = lua_tostring(L, 2);
      const char *usage = 0;

      for (const RegisterItem *item = items + 1; item->type; item++) {
        if (strcmp(function, "introduce") == 0)
          usage = LuaUtils_IntroduceUsage;
        if (strcmp(function, item->name) == 0)
          usage = item->usage;
        if (usage)
          break;
      }
      if (usage) {
        luaL_Buffer buffer;
        luaL_buffinit(L, &buffer);
        ExpandUsageToBuffer(&buffer, usage, library, function);
        luaL_pushresult(&buffer);
      } else {
        lua_pushstring(L, function);
        lua_gettable(L, -4);
        if (lua_isfunction(L, -1) && !lua_iscfunction(L, -1)) {
          Proto *proto = ((LClosure*) lua_topointer(L, -1))->p;
          luaL_Buffer buffer;
          luaL_buffinit(L, &buffer);
          luaL_addstring(&buffer, "[\"");
          luaL_addstring(&buffer, library);
          luaL_addchar(&buffer, '.');
          luaL_addstring(&buffer, function);
          luaL_addchar(&buffer, '(');
          for (uint16_t i = 0; i < proto->numparams; i++) {
            if (i) luaL_addchar(&buffer, ',');
            luaL_addstring(&buffer, getstr(proto->locvars[i].varname));
          }
          if (proto->is_vararg) {
            if (proto->numparams) luaL_addchar(&buffer, ',');
            luaL_addstring(&buffer, "...");
          }
          luaL_addstring(&buffer, ")\"]");
          luaL_pushresult(&buffer);
        } else
          lua_pushstring(L, "<unknown>");
      }
    }

  } else {

    luaL_Buffer buffer;
    luaL_buffinit(L, &buffer);
    luaL_addchar(&buffer, '[');

    uint16_t i = 0;
    {
      lua_pushnil(L);
      while (lua_next(L, -2)) {

        switch (lua_type(L, -1)) {

          case LUA_TBOOLEAN :
            // {"name":boolean},
            if (i++)
              luaL_addchar(&buffer, ',');
            luaL_addstring(&buffer, "{\"");
            luaL_addstring(&buffer, lua_tostring(L, -2));
            luaL_addstring(&buffer, "\":");
            luaL_addstring(&buffer, lua_toboolean(L, -1) ? "true" : "false");
            luaL_addchar(&buffer, '}');
            break;

          case LUA_TNUMBER :
            // {"name":number},
            if (i++)
              luaL_addchar(&buffer, ',');
            luaL_addstring(&buffer, "{\"");
            luaL_addstring(&buffer, lua_tostring(L, -2));
            luaL_addstring(&buffer, "\":");
            luaL_addstring(&buffer, lua_tostring(L, -1));
            luaL_addchar(&buffer, '}');
            break;

          case LUA_TUSERDATA :
          case LUA_TLIGHTUSERDATA :
            // "name",
            if (i++)
              luaL_addchar(&buffer, ',');
            luaL_addchar(&buffer, '"');
            luaL_addstring(&buffer, lua_tostring(L, -2));
            luaL_addchar(&buffer, '"');
            break;

        }
        lua_pop(L, 1);
      }
    }
    {
      lua_pushnil(L);
      while (lua_next(L, -2)) {
        if (lua_type(L, -1) == LUA_TFUNCTION) {
          // "name()",
          if (i++)
            luaL_addchar(&buffer, ',');
          luaL_addchar(&buffer, '"');
          luaL_addstring(&buffer, lua_tostring(L, -2));
          luaL_addstring(&buffer, "()\""); // TODO Hier "Usage"
        }
        lua_pop(L, 1);
      }
    }
    {
      lua_pushnil(L);
      while (lua_next(L, -2)) {
        if (lua_type(L, -1) == LUA_TTABLE) {
          // "name",
          if (i++)
            luaL_addchar(&buffer, ',');
          luaL_addchar(&buffer, '"');
          luaL_addstring(&buffer, lua_tostring(L, -2));
          luaL_addstring(&buffer, ".*\"");
        }
        lua_pop(L, 1);
      }
    }
    luaL_addchar(&buffer, ']');
    luaL_pushresult(&buffer);

  }
  return 1;
}
Esempio n. 25
0
qboolean CG_LuaStartVM(lvm_t * vm)
{
	int             res = 0;
	char            homepath[MAX_QPATH], gamepath[MAX_QPATH];

	vm->L = luaL_newstate();
	if(!vm->L)
	{
		LUA_LOG("Lua: Lua failed to initialise.\n");
		return qfalse;
	}

	luaL_openlibs(vm->L);

	trap_Cvar_VariableStringBuffer("fs_homepath", homepath, sizeof(homepath));
	trap_Cvar_VariableStringBuffer("fs_game", gamepath, sizeof(gamepath));

	lua_getglobal(vm->L, LUA_LOADLIBNAME);
	if(lua_istable(vm->L, -1))
	{
		lua_pushstring(vm->L, va("%s%s%s%s?.lua;%s%s%s%slualib%slua%s?.lua",
								 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP,
								 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP));
		lua_setfield(vm->L, -2, "path");
		lua_pushstring(vm->L, va("%s%s%s%s?.%s;%s%s%s%slualib%sclibs%s?.%s",
								 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, EXTENSION,
								 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP, EXTENSION));
		lua_setfield(vm->L, -2, "cpath");
	}
	lua_pop(vm->L, 1);

	Lua_RegisterGlobal(vm->L, "LUA_PATH", va("%s%s%s%s?.lua;%s%s%s%slualib%slua%s?.lua",
											 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP,
											 homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP));
	Lua_RegisterGlobal(vm->L, "LUA_CPATH", va("%s%s%s%s?.%s;%s%s%s%slualib%sclibs%s?.%s",
											  homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, EXTENSION,
											  homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP, EXTENSION));
	Lua_RegisterGlobal(vm->L, "LUA_DIRSEP", LUA_DIRSEP);

	lua_newtable(vm->L);
	Lua_RegConstInteger(vm->L, CS_PLAYERS);
	Lua_RegConstInteger(vm->L, EXEC_NOW);
	Lua_RegConstInteger(vm->L, EXEC_INSERT);
	Lua_RegConstInteger(vm->L, EXEC_APPEND);
	Lua_RegConstInteger(vm->L, FS_READ);
	Lua_RegConstInteger(vm->L, FS_WRITE);
	Lua_RegConstInteger(vm->L, FS_APPEND);
	Lua_RegConstInteger(vm->L, FS_APPEND_SYNC);
	Lua_RegConstInteger(vm->L, SAY_ALL);
	Lua_RegConstInteger(vm->L, SAY_TEAM);
	Lua_RegConstString(vm->L, HOSTARCH);

	luaopen_base(vm->L);
	luaopen_string(vm->L);
	luaopen_coroutine(vm->L);
	Luaopen_Qmath(vm->L);
	Luaopen_Vector(vm->L);

	res = luaL_loadbuffer(vm->L, vm->code, vm->code_size, vm->filename);
	if(res == LUA_ERRSYNTAX)
	{
		LUA_LOG("Lua: syntax error during pre-compilation: %s\n", (char *)lua_tostring(vm->L, -1));
		CG_Printf(S_COLOR_YELLOW "Lua: syntax error: %s\n", (char *)lua_tostring(vm->L, -1));
		lua_pop(vm->L, 1);
		vm->error++;
		return qfalse;
	}
	else if(res == LUA_ERRMEM)
	{
		LUA_LOG("Lua: memory allocation error #1 ( %s )\n", vm->filename);
		vm->error++;
		return qfalse;
	}

	if(!CG_LuaCall(vm, "CG_LuaStartVM", 0, 0))
		return qfalse;

	LUA_LOG("Lua: Loading %s\n", vm->filename);
	return qtrue;
}
Esempio n. 26
0
TOLUA_API void tolua_pushusertype (lua_State* L, void* value, const char* type)
{
    if (value == NULL)
        lua_pushnil(L);
    else
    {        
        luaL_getmetatable(L, type);                                 /* stack: mt */
        if (lua_isnil(L, -1)) { /* NOT FOUND metatable */
            lua_pop(L, 1);
            return;
        }
        lua_pushstring(L,"tolua_ubox");
        lua_rawget(L,-2);                                           /* stack: mt ubox */
        if (lua_isnil(L, -1)) {
            lua_pop(L, 1);
            lua_pushstring(L, "tolua_ubox");
            lua_rawget(L, LUA_REGISTRYINDEX);
        };
        
        lua_pushlightuserdata(L,value);                             /* stack: mt ubox key<value> */
        lua_rawget(L,-2);                                           /* stack: mt ubox ubox[value] */
        
        if (lua_isnil(L,-1))
        {
            lua_pop(L,1);                                           /* stack: mt ubox */
            lua_pushlightuserdata(L,value);
            *(void**)lua_newuserdata(L,sizeof(void *)) = value;     /* stack: mt ubox value newud */
            lua_pushvalue(L,-1);                                    /* stack: mt ubox value newud newud */
            lua_insert(L,-4);                                       /* stack: mt newud ubox value newud */
            lua_rawset(L,-3);                  /* ubox[value] = newud, stack: mt newud ubox */
            lua_pop(L,1);                                           /* stack: mt newud */
            /*luaL_getmetatable(L,type);*/
            lua_pushvalue(L, -2);                                   /* stack: mt newud mt */
            lua_setmetatable(L,-2);                      /* update mt, stack: mt newud */

#ifdef LUA_VERSION_NUM
            lua_pushvalue(L, TOLUA_NOPEER);
            lua_setfenv(L, -2);
#endif
        }
        else
        {
            /* check the need of updating the metatable to a more specialized class */
            lua_insert(L,-2);                                       /* stack: mt ubox[u] ubox */
            lua_pop(L,1);                                           /* stack: mt ubox[u] */
            lua_pushstring(L,"tolua_super");
            lua_rawget(L,LUA_REGISTRYINDEX);                        /* stack: mt ubox[u] super */
            lua_getmetatable(L,-2);                                 /* stack: mt ubox[u] super mt */
            lua_rawget(L,-2);                                       /* stack: mt ubox[u] super super[mt] */
            if (lua_istable(L,-1))
            {
                lua_pushstring(L,type);                             /* stack: mt ubox[u] super super[mt] type */
                lua_rawget(L,-2);                                   /* stack: mt ubox[u] super super[mt] flag */
                if (lua_toboolean(L,-1) == 1)                       /* if true */
                {
                    lua_pop(L,3);                                   /* mt ubox[u]*/
                    lua_remove(L, -2);
                    return;
                }
            }
            /* type represents a more specilized type */
            /*luaL_getmetatable(L,type);             // stack: mt ubox[u] super super[mt] flag mt */
            lua_pushvalue(L, -5);                    /* stack: mt ubox[u] super super[mt] flag mt */
            lua_setmetatable(L,-5);                /* stack: mt ubox[u] super super[mt] flag */
            lua_pop(L,3);                          /* stack: mt ubox[u] */
        }
        lua_remove(L, -2);    /* stack: ubox[u]*/
    }
}
Esempio n. 27
0
static int openssl_ocsp_request_new(lua_State*L)
{
  OCSP_REQUEST *req = NULL;

  if (lua_isstring(L, 1))
  {
    BIO* bio = load_bio_object(L, 1);
    req = d2i_OCSP_REQUEST_bio(bio, NULL);
    /*
    if (!req)
    {
      BIO_reset(bio);
      req = PEM_read_bio_OCSP_REQUEST(bio, NULL, NULL);
    }
    */
    BIO_free(bio);
  }
  else
  {
    X509 *issuer = CHECK_OBJECT(1, X509, "openssl.x509");
    X509_NAME *iname = X509_get_subject_name(issuer);
    ASN1_BIT_STRING *ikey = X509_get0_pubkey_bitstr(issuer);

    OCSP_CERTID *id = NULL;
    OCSP_ONEREQ *one;
    char buf[1024];
    int nonce = lua_gettop(L) > 2 ? auxiliar_checkboolean(L, 3) : 0;
    req = OCSP_REQUEST_new();

    if (lua_istable(L, 2))
    {
      int len = lua_rawlen(L, 2);
      int i;
      for (i = 1; i <= len; i++)
      {
        lua_rawgeti(L, 2, i);
        if (auxiliar_isclass(L, "openssl.x509", -1))
        {
          X509 *cert = CHECK_OBJECT(2, X509, "openssl.x509");
          id = OCSP_cert_to_id(NULL, cert, issuer);
          one = OCSP_request_add0_id(req, id);
        }
        else
        {
          size_t len;
          char *serial = (char *)luaL_checklstring(L, -1, &len);
          ASN1_INTEGER *sno = ASN1_INTEGER_new();
          BIO* bio = BIO_new(BIO_s_mem());
          BIO_write(bio, serial, len);
          if (a2i_ASN1_INTEGER(bio, sno, buf, 1024) == 1)
          {
            id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
            one = OCSP_request_add0_id(req, id);
          };
          ASN1_INTEGER_free(sno);
          BIO_free(bio);
        }
        lua_pop(L, 1);
      }
    }
    else if (auxiliar_isclass(L, "openssl.x509", 2))
    {
      X509 *cert = CHECK_OBJECT(2, X509, "openssl.x509");
      id = OCSP_cert_to_id(NULL, cert, issuer);
      one = OCSP_request_add0_id(req, id);
    }
    else
    {
      ASN1_INTEGER *sno = ASN1_INTEGER_new();
      BIO* bio = load_bio_object(L, 2);

      if (a2i_ASN1_INTEGER(bio, sno, buf, 1024) == 1)
      {
        id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
        one = OCSP_request_add0_id(req, id);
      };
      ASN1_INTEGER_free(sno);
      BIO_free(bio);
    }
    if (nonce)
      OCSP_request_add1_nonce(req, NULL,  -1);
  }
  if (req)
  {
    PUSH_OBJECT(req, "openssl.ocsp_request");
  }
  else
    lua_pushnil(L);

  return 1;
}
Esempio n. 28
0
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);

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

        // 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);
      ffi_stream_add_string(&bodystream, (const char *)d.buffer, d.total);
      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;
}
Esempio n. 29
0
void pp_lua_handle(struct pp_state* state, void* scanner, bstring name, list_t* parameters)
{
	struct lua_preproc* pp;
	struct customarg_entry* carg;
	char* cstr;
	bstring dot;
	unsigned int i;
	int paramtbl;

	// Convert the name to lowercase.
	btolower(name);
	cstr = bstr2cstr(name, '0');

	// Loop through all of the modules.
	list_iterator_start(&modules);
	while (list_iterator_hasnext(&modules))
	{
		pp = list_iterator_next(&modules);

		// Set stack top (I don't know why the top of the
		// stack is negative!)
		lua_settop(pp->state, 0);

		// Search handler table for entries.
		lua_getglobal(pp->state, HANDLER_TABLE_NAME);
		lua_getfield(pp->state, -1, cstr);
		if (!lua_istable(pp->state, -1))
		{
			// No such entry.
			lua_pop(pp->state, 2);
			continue;
		}

		// Call the handler function.
		lua_getfield(pp->state, -1, HANDLER_FIELD_FUNCTION_NAME);
		pp_lua_push_state(pp, state, scanner);
		lua_newtable(pp->state);
		paramtbl = lua_gettop(pp->state);
		for (i = 0; i < list_size(parameters); i++)
		{
			carg = list_get_at(parameters, i);

			lua_newtable(pp->state);
			if (carg->expr != NULL)
				lua_pushstring(pp->state, "EXPRESSION");
			else if (carg->string != NULL)
				lua_pushstring(pp->state, "STRING");
			else if (carg->word != NULL)
				lua_pushstring(pp->state, "WORD");
			else
				lua_pushstring(pp->state, "NUMBER");
			lua_setfield(pp->state, -2, "type");
			if (carg->expr != NULL)
				luaX_pushexpression(pp->state, carg->expr);
			else if (carg->string != NULL)
				lua_pushstring(pp->state, carg->string->data);
			else if (carg->word != NULL)
				lua_pushstring(pp->state, carg->word->data);
			else
				lua_pushnumber(pp->state, carg->number);
			lua_setfield(pp->state, -2, "value");
			lua_rawseti(pp->state, paramtbl, i + 1);
		}
		if (lua_pcall(pp->state, 2, 0, 0) != 0)
		{
			printd(LEVEL_ERROR, "error: unable to call preprocessor handler for '%s'.\n", name->data);
			printd(LEVEL_ERROR, "%s\n", lua_tostring(pp->state, -1));
			bdestroy(name);
			bcstrfree(cstr);
			lua_pop(pp->state, 2);
			list_iterator_stop(&modules);
			list_destroy(parameters);
			return;
		}

		bdestroy(name);
		bcstrfree(cstr);
		lua_pop(pp->state, 2);
		list_iterator_stop(&modules);
		list_destroy(parameters);
		return;
	}
	list_iterator_stop(&modules);

	// There is no custom preprocessor module that handles this directive, however
	// it could be a directive that is recognised by the underlying assembler / compiler,
	// so pass it through as output.
	dot = bfromcstr(".");
	bconcat(dot, name);
	btoupper(dot);
	bconchar(dot, ' ');
	list_iterator_start(parameters);
	while (list_iterator_hasnext(parameters))
	{
		carg = list_iterator_next(parameters);

		// Output the parameter based on the type.
		if (carg->word != NULL)
			bconcat(dot, carg->word);
		else if (carg->string != NULL)
		{
			bconchar(dot, '"');
			bescape(carg->string);
			bconcat(dot, carg->string);
			bconchar(dot, '"');
		}
		else
			bformata(dot, "%i", carg->number);
	}
	list_iterator_stop(parameters);
	handle_pp_lua_print_line(dot->data, scanner);

	// Clean up.
	list_destroy(parameters);
	bdestroy(name);
	bcstrfree(cstr);
}
Esempio n. 30
0
static int lua_iso8583_pack(lua_State *L)
{
	iso8583_userdata *iso8583u;
	char error[BUFSIZ];
	int n = lua_gettop(L);
	unsigned int iso8583_maxsize = ISO8583_MAXSIZE;
	unsigned char iso8583_data[ISO8583_MAXSIZE];

	if (n < 2) {
		lua_pushnil(L);
		lua_pushstring(L, "arguments error! too small!");
		return 2;
	}

	iso8583u = (iso8583_userdata *)luaL_checkudata(L, 1, "iso8583");

	if (!lua_istable(L, 2)) {
        lua_pushnil(L);
        lua_pushstring(L, "argument error! data must be table!");
        return 2;
    } 

	lua_pushnil(L);
	while(lua_next(L, 2) != 0) {

		if (lua_isnumber(L, -2)) {
			int i = lua_tointeger(L, -2);
			
			if (i >= 0 && i <= 128) {
				size_t size;
				const unsigned char *data;

				if (!lua_isstring(L, -1)) {
					lua_pushnil(L);
					snprintf(error, BUFSIZ, "data %d error! is not a string!", i);
					lua_pushstring(L, error);
					return 2;
				}

				data = (const unsigned char *)lua_tolstring(L, -1, &size);

				if (iso8583_set(iso8583u->handle, i, data, (unsigned int)size) != ISO8583_OK) {
					lua_pushnil(L);
					snprintf(error, BUFSIZ, "data %d error!", i);
					lua_pushstring(L, error);
					return 2;
				}
			}
		}

		lua_pop(L, 1);
	}

	lua_pop(L, 1);

	if (iso8583_pack(iso8583u->handle, iso8583_data, &iso8583_maxsize) != ISO8583_OK) {
		lua_pushnil(L);
		snprintf(error, BUFSIZ, "pack iso8583 error! %s", iso8583u->handle->error);
        lua_pushstring(L, error);
		return 2;
	}

	lua_pushlstring(L, (const char *)iso8583_data, iso8583_maxsize);
	
	return 1;
}