コード例 #1
0
ファイル: barrier_api.cpp プロジェクト: jorikvdwerf/Tortuga
static int setStatus(lua_State* L) {
	BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
	barrier->SetStatus(lua_tointeger(L, 2) - 1, lua_tointeger(L, 3));
	return 0;
}
コード例 #2
0
ファイル: lauxlib.c プロジェクト: monkey0506/lua51src
static int checkint (lua_State *L, int topop) {
  int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
  lua_pop(L, topop);
  return n;
}
コード例 #3
0
static int setMessageInt(lua_State* L)
{
	ActiveDuel->currentMessage.addValue(lua_tostring(L, 1), std::to_string(lua_tointeger(L, 2)));
	return 0;
}
コード例 #4
0
ファイル: LuaRegManLib.cpp プロジェクト: hjpotter92/PtokaX
static int ChangeReg(lua_State * L) {
	if(lua_gettop(L) != 3) {
        luaL_error(L, "bad argument count to 'ChangeReg' (3 expected, got %d)", lua_gettop(L));
        lua_settop(L, 0);
        lua_pushnil(L);
        return 1;
    }

    if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 3) != LUA_TNUMBER) {
        luaL_checktype(L, 1, LUA_TSTRING);
        luaL_checktype(L, 3, LUA_TNUMBER);
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

    size_t szNickLen, szPassLen = 0;
    char * sNick = (char *)lua_tolstring(L, 1, &szNickLen);
    char * sPass = NULL;

    if(lua_type(L, 2) == LUA_TSTRING) {
        sPass = (char *)lua_tolstring(L, 2, &szPassLen);
        if(szPassLen == 0 || szPassLen > 64 || strpbrk(sPass, "|") != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }
    } else if(lua_type(L, 2) != LUA_TNIL) {
        luaL_checktype(L, 2, LUA_TSTRING);
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

#if LUA_VERSION_NUM < 503
	uint16_t i16Profile = (uint16_t)lua_tonumber(L, 3);
#else
	uint16_t i16Profile = (uint16_t)lua_tointeger(L, 3);
#endif

	if(i16Profile > clsProfileManager::mPtr->ui16ProfileCount-1 || szNickLen == 0 || szNickLen > 64 || strpbrk(sNick, " $|") != NULL) {
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

	RegUser *reg = clsRegManager::mPtr->Find(sNick, szNickLen);

    if(reg == NULL) {
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

    clsRegManager::mPtr->ChangeReg(reg, sPass, i16Profile);

    lua_settop(L, 0);

    lua_pushboolean(L, 1);
    return 1;
}
コード例 #5
0
ファイル: CvLuaLeague.cpp プロジェクト: Be1eriand/Civ5-DLL
//------------------------------------------------------------------------------
//string GetLeagueSplashNextEraDetails(LeagueSpecialSessionTypes eGoverningSpecialSession, bool bJustFounded);
int CvLuaLeague::lGetLeagueSplashNextEraDetails(lua_State* L)
{
	CvLeague* pLeague = GetInstance(L);
	const LeagueSpecialSessionTypes eGoverningSpecialSession = (LeagueSpecialSessionTypes) lua_tointeger(L, 2);
	const bool bJustFounded = lua_toboolean(L, 3);

	CvString sValue = pLeague->GetLeagueSplashNextEraDetails(eGoverningSpecialSession, bJustFounded);
	lua_pushstring(L, sValue.c_str());
	return 1;
}
コード例 #6
0
void IntFromLua(lua_State *L, int index, Variable *ref)
{
    assert(lua_isnumber(L, index));
    int temp = lua_tointeger(L, index);
    ref->SetData(ref->Meta()->NewCopy(&temp));
}
コード例 #7
0
ファイル: stack_get.hpp プロジェクト: iz2140/Sol2Test
 static T get(lua_State* L, int index = -1) {
     return static_cast<T>(lua_tointeger(L, index));
 }
コード例 #8
0
ファイル: serialize.c プロジェクト: twitter/torch-ipc
static int rb_load_rcsv(lua_State *L, ringbuffer_t *rb, int is_key) {
   char type;
   lua_Number n;
   lua_Integer ni;
   char *str;
   size_t str_len;
   int ret;
   chunked_t chunked;
   void *ptr, **pptr;

   if (!lua_checkstack(L, 1)) return -ENOMEM;
   RB_READ(L, rb, &type, sizeof(type));
   switch (type) {
      case LUA_TNIL:
         if (is_key) return 0;
         lua_pushnil(L);
         return 1;
      case LUA_TBOOLEAN:
         RB_READ(L, rb, &type, sizeof(char));
         lua_pushboolean(L, type);
         return 1;
      case LUA_TNUMBER:
         RB_READ(L, rb, &n, sizeof(n));
         lua_pushnumber(L, n);
         return 1;
      case EXTRA_LUA_TINTEGER:
         RB_READ(L, rb, &ni, sizeof(ni));
         lua_pushinteger(L, ni);
         return 1;
      case LUA_TSTRING:
         RB_READ(L, rb, &str_len, sizeof(str_len));
         str = alloca(str_len);
         RB_READ(L, rb, str, str_len);
         lua_pushlstring(L, str, str_len);
         return 1;
      case LUA_TTABLE:
         lua_newtable(L);
         while (1) {
            ret = rb_load_rcsv(L, rb, 1); // key
            if (!ret) break;
            rb_load_rcsv(L, rb, 0); // value
            lua_settable(L, -3);
         }

         // read typename
         RB_READ(L, rb, &str_len, sizeof(str_len));
         str = alloca(str_len + 1);
         RB_READ(L, rb, str, str_len);
         str[str_len] = 0;

         if (str_len > 0) { 
            luaL_getmetatable(L, str);
            lua_setmetatable(L, -2);
         }

         return 1;
      case LUA_TFUNCTION:
         chunked.rb = rb;
         chunked.read_last = 0;
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
         ret = lua_load(L, rb_lua_reader, &chunked, NULL);
#else
         ret = lua_load(L, rb_lua_reader, &chunked, NULL, NULL);
#endif

         if (ret) return -EINVAL;
         // LuaJIT reads the last 0 marker, regular Lua does not, even it out.
         if (!chunked.read_last) {
            RB_READ(L, rb, &str_len, sizeof(str_len));
         }

         // are we expecting upvalues?
         int upval;
         RB_READ(L, rb, &upval, sizeof(int));

         if (upval == 1) {
            // read upvalue index of _ENV
            int envIdx;
            RB_READ(L, rb, &envIdx, sizeof(int));

            // read table of upvalues
            rb_load_rcsv(L, rb, 0);

            // set _ENV
            if (envIdx > 0) {
               lua_getglobal(L, "_G");
               lua_setupvalue(L, -3, envIdx);
            }

            // set function upvalues
            int top = lua_gettop(L);
            lua_pushnil(L);
            while (lua_next(L, top) != 0) {
               lua_Integer n = lua_tointeger(L, top + 1); // key
               lua_setupvalue(L, -4, n);
            }

            lua_pop(L, 1); 
         }

         return 1;
      case LUA_TUSERDATA:
      case -LUA_TUSERDATA:
         RB_READ(L, rb, &str_len, sizeof(str_len));
         str = alloca(str_len + 1);
         RB_READ(L, rb, str, str_len);
         RB_READ(L, rb, &ptr, sizeof(void *));
         str[str_len] = 0;
         if (type >= 0) {
            luaT_pushudata(L, ptr, str);
         } else {
            pptr = (void **)lua_newuserdata(L, sizeof(void **));
            *pptr = ptr;
            luaL_getmetatable(L, str);
            lua_setmetatable(L, -2);
         }
         return 1;
      default:
         return -EINVAL;
   }
}
コード例 #9
0
ファイル: serialize.c プロジェクト: twitter/torch-ipc
int rb_save(lua_State *L, int index, ringbuffer_t *rb, int oop, int upval) {
   char type = lua_type(L, index);
   switch (type) {
      case LUA_TNIL: {
         RB_WRITE(L, rb, &type, sizeof(char));
         return 0;
      }
      case LUA_TBOOLEAN: {
         RB_WRITE(L, rb, &type, sizeof(char));
         type = lua_toboolean(L, index);
         RB_WRITE(L, rb, &type, sizeof(char));
         return 0;
      }
      case LUA_TNUMBER: {
#if LUA_VERSION_NUM >= 503
         if (lua_isinteger(L, index)) {
            type = EXTRA_LUA_TINTEGER;
            RB_WRITE(L, rb, &type, sizeof(char));
            lua_Integer n = lua_tointeger(L, index);
            RB_WRITE(L, rb, &n, sizeof(n));
         } else
#endif
         {
            RB_WRITE(L, rb, &type, sizeof(char));
            lua_Number n = lua_tonumber(L, index);
            RB_WRITE(L, rb, &n, sizeof(n));
         }
         return 0;
      }
      case LUA_TSTRING: {
         RB_WRITE(L, rb, &type, sizeof(char));
         size_t str_len;
         const char *str = lua_tolstring(L, index, &str_len);
         RB_WRITE(L, rb, &str_len, sizeof(str_len));
         RB_WRITE(L, rb, str, str_len);
         return 0;
      }
      case LUA_TTABLE: {
         RB_WRITE(L, rb, &type, sizeof(char));
         int top = lua_gettop(L);
         int ret;

         lua_pushnil(L);
         while (lua_next(L, index) != 0) {
            ret = rb_save(L, top + 1, rb, oop, upval); // key
            if (ret) {
               lua_pop(L, 2);
               return ret;
            }
            ret = rb_save(L, top + 2, rb, oop, upval); // value
            if (ret) {
               lua_pop(L, 2);
               return ret;
            }
            lua_pop(L, 1);
         }
         type = LUA_TNIL;
         RB_WRITE(L, rb, &type, sizeof(char)); // breaks the read loop

         // the typename identifies the metatable
         const char *str = luaT_typename(L, index);
         if (!str) {
            if (luaL_callmeta(L, index, "metatablename")) {
               str = lua_tostring(L, lua_gettop(L));
               lua_pop(L, 1);
            } else {
               str = "";
            }
         }
         size_t str_len = strlen(str);
         RB_WRITE(L, rb, &str_len, sizeof(str_len));
         RB_WRITE(L, rb, str, str_len);
         return 0;
      }
      case LUA_TFUNCTION: {

         RB_WRITE(L, rb, &type, sizeof(char));
         if (index != lua_gettop(L)) {
            lua_pushvalue(L, index);
         }
         lua_Debug ar;
         lua_pushvalue(L, -1);
         lua_getinfo(L, ">nuS", &ar);
         if (ar.what[0] != 'L') {
             luaL_error(L, "attempt to persist a C function '%s'", ar.name);
         }
         
         // this returns different things under LuaJIT vs Lua
#if LUA_VERSION_NUM >= 503
         lua_dump(L, rb_lua_writer, rb, 0);
#else
         lua_dump(L, rb_lua_writer, rb);
#endif

         size_t str_len = 0;
         RB_WRITE(L, rb, &str_len, sizeof(size_t)); // zero-terminated

         // does the serialization accept upvalues?
         RB_WRITE(L, rb, &upval, sizeof(int)); 
         
         // upvalues
         if (upval == 1) {
            lua_newtable(L);
            int envIdx = -1;
            for (int i=1; i <= ar.nups; i++) {
               const char *name = lua_getupvalue(L, -2, i);
               if (strcmp(name, "_ENV") != 0) { 
                  lua_rawseti(L, -2, i);
               } else { // ignore _ENV as we assume that this is the global _G variable
                  lua_pop(L, 1);
                  envIdx = i;
               }
            }
            // write upvalue index of _ENV
            RB_WRITE(L, rb, &envIdx, sizeof(int));

            // write upvalue table
            int ret = rb_save(L, lua_gettop(L), rb, oop, upval);
            if (ret) {
               return ret;
            }
            lua_pop(L, 1);
         } else if (ar.nups > 1) {
            luaL_error(L, "attempt to serialize a funciton with upvalues (i.e. a closure). Use ipc.workqueue.writeup().");
         }

         if (index != lua_gettop(L)) {
            lua_pop(L, 1);
         }

         return 0;
      }
      case LUA_TUSERDATA: {
         if (oop) return -EPERM;
         const char *str = luaT_typename(L, index);
         if (!str) {
            if (luaL_callmeta(L, index, "metatablename")) {
               str = lua_tostring(L, lua_gettop(L));
               lua_pop(L, 1);
               type = -type;
            } else {
               return -EINVAL;
            }
         }
         RB_WRITE(L, rb, &type, sizeof(char));
         size_t str_len = strlen(str);
         RB_WRITE(L, rb, &str_len, sizeof(str_len));
         RB_WRITE(L, rb, str, str_len);
         void *ptr = lua_touserdata(L, index);
         RB_WRITE(L, rb, ptr, sizeof(void *));
         if (luaL_callmeta(L, index, "retain")) {
            lua_pop(L, 1);
         } else {
            return -EINVAL;
         }
         return 0;
      }
      default:
         return -EPERM;
   }
}
コード例 #10
0
ファイル: pbc-lua.cpp プロジェクト: xvly/fish
static void
_get_array_value(lua_State *L, pbc_array array, char type) {
	switch(type) {
		case 'I': {
			int32_t v = luaL_checkinteger(L, -1);
			uint32_t hi = 0;
			if (v<0) {
				hi = ~0;
			}
			pbc_array_push_integer(array, v, hi);
			break;
		}
		case 'U' : {
			uint64_t v = (uint64_t)luaL_checknumber(L, -1);
			pbc_array_push_integer(array, (uint32_t)v, (uint32_t)(v >> 32));
			break;
		}
		case 'D' : {
			int64_t v = (int64_t)luaL_checknumber(L, -1);
			pbc_array_push_integer(array, (uint32_t)v, (uint32_t)(v >> 32));
			break;
		}
		case 'B': {
			int32_t v = lua_toboolean(L, -1);
			pbc_array_push_integer(array, v ? 1: 0, 0);
			break;
		}
		case 'P': {
			void *p = lua_touserdata(L, -1);
			uint32_t v = (uint32_t)(intptr_t)p;
			pbc_array_push_integer(array, v, 0);
			break;
		}
		case 'X': {
			const char * i64 = luaL_checkstring(L, -1);
			uint64_t v = *(uint64_t *)i64;
			pbc_array_push_integer(array, (uint32_t)v, (uint32_t)(v >> 32));
			break;
		}
		case 'R': {
			double v = luaL_checknumber(L, -1);
			pbc_array_push_real(array, v);
			break;
		}
		case 'S': {
			size_t sz = 0;
			const char * str = luaL_checklstring(L, -1, &sz);
			struct pbc_slice slice;
			slice.buffer = (void*)str;
			slice.len = sz;
			pbc_array_push_slice(array, &slice);
			break;
		}
		case 'M': {
			struct pbc_slice slice;
			if (lua_istable(L,-1)) {
				lua_rawgeti(L,-1,1);
				slice.buffer = lua_touserdata(L,-1);
				lua_rawgeti(L,-2,2);
				slice.len = lua_tointeger(L,-1);
				lua_pop(L,2);
			} else {
				size_t sz = 0;
				const char * buffer = luaL_checklstring(L, -1, &sz);
				slice.buffer = (void *)buffer;
				slice.len = sz;
			}
			pbc_array_push_slice(array, &slice);
			break;
		}
	}
}
コード例 #11
0
ファイル: pbc-lua.cpp プロジェクト: xvly/fish
/*
	lightuserdata pattern
	string format "ixrsmbp"
	integer size
 */
static int
_pattern_pack(lua_State *L) {
	struct pbc_pattern * pat = (struct pbc_pattern *)checkuserdata(L,1);
	if (pat == NULL) {
		return luaL_error(L, "pack pattern is NULL");
	}
	size_t format_sz = 0;
	const char * format = lua_tolstring(L,2,&format_sz);
	int size = lua_tointeger(L,3);

	char * data = (char *)alloca(size);
//	A trick , we don't need default value. zero buffer for array and message field.
//	pbc_pattern_set_default(pat, data);
	memset(data, 0 , size);

	char * ptr = data;

    size_t i;

	for (i=0;i<format_sz;i++) {
		if (format[i] >= 'a' && format[i] <='z') {
			ptr = _get_value(L, 4+i, ptr, format[i]);
		} else {
			if (!lua_istable(L,4+i)) {
				luaL_error(L,"need table for array type");
			}
			int j;
			int n = lua_rawlen(L,4+i);
			for (j=0;j<n;j++) {
				lua_rawgeti(L,4+i,j+1);
				_get_array_value(L,(struct _pbc_array *)ptr,format[i]);
				lua_pop(L,1);
			}
			ptr += sizeof(pbc_array);
		}
	}

	luaL_Buffer b;
	UNUSED(&b);
	luaL_buffinit(L, &b);

	int cap = 128;
	for (;;) {
		char * temp = (char *)luaL_prepbuffsize(&b , cap);

		struct pbc_slice slice;
		slice.buffer = temp;
		slice.len = cap;

		int ret = pbc_pattern_pack(pat, data, &slice);

		if (ret < 0) {
			cap = cap * 2;
			_Free(temp);
			continue;
		}

		luaL_addsize(&b , slice.len);
		break;
	}
	luaL_pushresult(&b);

	pbc_pattern_close_arrays(pat, data);
	return 1;
}
コード例 #12
0
ファイル: pbc-lua.cpp プロジェクト: xvly/fish
static char *
_get_value(lua_State *L, int index, char * ptr, char type) {
	switch(type) {
		case 'i': {
			int32_t v = luaL_checkinteger(L, index);
			memcpy(ptr, &v, 4);
			return ptr + 4;
		}
		case 'u': {
			uint64_t v = (uint64_t)luaL_checknumber(L, index);
			memcpy(ptr, &v, 8);
			return ptr + 8;
		}
		case 'd': {
			int64_t v = (int64_t)luaL_checknumber(L, index);
			memcpy(ptr, &v, 8);
			return ptr + 8;
		}
		case 'b': {
			int32_t v = lua_toboolean(L, index);
			memcpy(ptr, &v, 4);
			return ptr + 4;
		}
		case 'p': {
			void *p = lua_touserdata(L, index);
			uint32_t v = (uint32_t)(intptr_t)p;
			memcpy(ptr, &v , 4);
			return ptr + 4;
		}
		case 'x': {
			const char * i64 = luaL_checkstring(L, index);
			memcpy(ptr, i64, 8);
			return ptr + 8;
		}
		case 'r': {
			double v = luaL_checknumber(L, index);
			memcpy(ptr, &v, 8);
			return ptr + 8;
		}
		case 's': {
			size_t sz = 0;
			const char * str = luaL_checklstring(L, index, &sz);
			struct pbc_slice * slice = (struct pbc_slice *)ptr;
			slice->buffer = (void*)str;
			slice->len = sz;
			return ptr + sizeof(struct pbc_slice);
		}
		case 'm': {
			struct pbc_slice * slice = (struct pbc_slice *)ptr;
			if (lua_istable(L,index)) {
				lua_rawgeti(L,index,1);
				slice->buffer = lua_touserdata(L,-1);
				lua_rawgeti(L,index,2);
				slice->len = lua_tointeger(L,-1);
				lua_pop(L,2);
			} else {
				size_t sz = 0;
				const char * buffer = luaL_checklstring(L, index, &sz);
				slice->buffer = (void *)buffer;
				slice->len = sz;
			}
			return ptr + sizeof(struct pbc_slice);
		}
		default:
			luaL_error(L,"unknown format %c", type);
			return ptr;
	}
}
コード例 #13
0
ファイル: Dump.cpp プロジェクト: GenexTeam/Genex
int MyCPrint( lua_State* L )
{
	// 获取参数数量
	int nArgs = lua_gettop(L);

	for (int i = 1; i <= nArgs; i++)
	{
		// 获取参数类型
		size_t nLen = 0;
		int bRet = 0;
		LUA_INTEGER nRet = 0;
		LUA_NUMBER dblRet = 0;
		const void* pAddr = NULL;
		const char* szRet = NULL;
		lua_State* pL = NULL;
		lua_CFunction pFunc = 0;

		int nType = lua_type(L, i);
		switch (nType)
		{
		case LUA_TNIL:
			printf("参数 %d 类型为:NIL\n", i);
			break;

		case LUA_TBOOLEAN:
			bRet = lua_toboolean(L, i);
			printf("参数 %d 类型为:BOOLEAN value = %s\n", i, (!!bRet ? "true" : "false"));
			break;

		case LUA_TLIGHTUSERDATA:
			pAddr = lua_touserdata(L, i);
			printf("参数 %d 类型为:LIGHTUSERDATA pointer = 0x%08X\n", i, (int)pAddr);
			break;

		case LUA_TNUMBER:
			nRet = lua_tointeger(L, i);
			dblRet = lua_tonumber(L, i);
			if (nRet < dblRet) // 浮点数
			{
				printf("参数 %d 类型为:NUMBER value = %g\n", i, dblRet);
			}
			else
			{
				printf("参数 %d 类型为:NUMBER value = %ld\n", i, nRet);
			}
			break;

		case LUA_TSTRING:
			nLen = lua_objlen(L, i);
			szRet = lua_tostring(L, i);
			printf("参数 %d 类型为:STRING len = %u value = %s\n", i, nLen, szRet);
			break;

		case LUA_TTABLE:
			nLen = lua_objlen(L, i);
			pAddr = lua_topointer(L, i);
			printf("参数 %d 类型为:TABLE len = %u pointer = 0x%p\n", i, nLen, (int)pAddr);
			break;

		case LUA_TFUNCTION:
			nLen = lua_objlen(L, i);
			pFunc = lua_tocfunction(L, i);
			printf("参数 %d 类型为:FUNCTION len = %u pointer = 0x%p\n", i, nLen, (int)pFunc);
			break;

		case LUA_TUSERDATA:
			pAddr = lua_touserdata(L, i);
			printf("参数 %d 类型为:USERDATA pointer = 0x%p\n", i, (int)pAddr);
			break;

		case LUA_TTHREAD:
			pL = lua_tothread(L, i);
			printf("参数 %d 类型为:THREAD pointer = 0x%p\n", i, (int)pL);
			break;

		default:
			nLen = lua_objlen(L, i);
			szRet = lua_typename(L, i);
			printf("参数 %d 类型未知!len = %u typename = %s\n", i, nLen, szRet);
			break;
		}
	}

	return 0;
}
コード例 #14
0
ファイル: barrier_api.cpp プロジェクト: jorikvdwerf/Tortuga
static int getStatus(lua_State* L) {
	BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
	lua_pushinteger(L, barrier->GetStatus(lua_tointeger(L, 2) - 1));
	return 1;
}
コード例 #15
0
ファイル: EnumHelper.cpp プロジェクト: raymoo/stepmania
int CheckEnum( lua_State *L, LuaReference &table, int iPos, int iInvalid, const char *szType, bool bAllowInvalid, bool bAllowAnything )
{
	luaL_checkany( L, iPos );

	if( lua_isnil(L, iPos) )
	{
		if( bAllowInvalid )
			return iInvalid;

		LuaHelpers::Push( L, ssprintf("Expected %s; got nil", szType) );
		lua_error( L );
	}

	iPos = LuaHelpers::AbsIndex( L, iPos );

	table.PushSelf( L );
	lua_pushvalue( L, iPos );
	lua_gettable( L, -2 );

	// If not found, check case-insensitively for legacy compatibility
	if( lua_isnil(L, -1) && lua_isstring(L, iPos) ) {
		RString sLower;

		// Get rid of nil value on stack
		lua_pop( L, 1 );

		// Get the string and lowercase it
		lua_pushvalue( L, iPos );
		LuaHelpers::Pop( L, sLower );
		sLower.MakeLower();

		// Try again to read the value
		table.PushSelf( L );
		LuaHelpers::Push( L, sLower );
		lua_gettable( L, -2 );
	}

	// If the result is nil, then a string was passed that is not a member of this enum.  Throw
	// an error.  To specify the invalid value, pass nil.  That way, typos will throw an error,
	// and not silently result in nil, or an out-of-bounds value.
	if( unlikely(lua_isnil(L, -1)) )
	{
		RString sGot;
		if( lua_isstring(L, iPos) )
		{
			/* We were given a string, but it wasn't a valid value for this enum.  Show
			 * the string. */
			lua_pushvalue( L, iPos );
			LuaHelpers::Pop( L, sGot );
			sGot = ssprintf( "\"%s\"", sGot.c_str() );
		}
		else
		{
			/* We didn't get a string.  Show the type. */
			luaL_pushtype( L, iPos );
			LuaHelpers::Pop( L, sGot );
		}
		LuaHelpers::Push( L, ssprintf("Expected %s; got %s", szType, sGot.c_str() ) );
		// There are a couple places where CheckEnum is used outside of a
		// function called from lua.  If we use lua_error from one of them,
		// StepMania crashes out completely.  bAllowAnything allows those places
		// to avoid crashing over theme mistakes.
		if(bAllowAnything)
		{
			RString errmsg;
			LuaHelpers::Pop(L, errmsg);
			LOG->Warn(errmsg.c_str());
			lua_pop(L, 2);
			return iInvalid;
		}
		lua_error( L );
	}
	int iRet = lua_tointeger( L, -1 );
	lua_pop( L, 2 );
	return iRet;
}
コード例 #16
0
ファイル: frontend_bindings.c プロジェクト: MSylvia/luxinia1
int  LuaBinding_GetWindowParam( int key )
{
  int stacksize;
  l_Lstack = lua_gettop(l_L);
  lua_pushnumber(l_L,key);
  if (callfunction(l_L,1,LUXI_FALSE,"LXFGetWindowParam")) {
    printpoperror();
    return LUXI_TRUE;
  }
  stacksize = lua_gettop(l_L);
  if (stacksize - l_Lstack == 1){
    int pos = lua_type(l_L,stacksize)== LUA_TBOOLEAN ? (int)lua_toboolean(l_L,stacksize) : (int)lua_tointeger(l_L,stacksize);
    lua_settop(l_L,l_Lstack);
    return pos;
  }
  else{
    lua_settop(l_L,l_Lstack);
    return LUXI_TRUE;
  }
}
コード例 #17
0
ファイル: handler.c プロジェクト: hivesolutions/viriatum
int _lua_write_connection(lua_State *lua_state) {
    /* allocates the data (original message data) */
    const char *data;

    /* allocates the (final) buffer to send the message */
    unsigned char *buffer;

    /* allocates the data size */
    unsigned int data_size;

    /* allocates the HTTP parser */
    struct http_parser_t *http_parser;

    /* allocates the connection */
    struct connection_t *connection;

    /* retrieves the number of (received) arguments */
    unsigned int number_arguments = lua_gettop(lua_state);

    /* in case the number of arguments is invalid */
    if(number_arguments != 3) {
        /* prints a warning message */
        V_WARNING("Invalid number of arguments\n");

        /* pushes an error message to Lua */
        lua_pushstring(lua_state, "Invalid number of arguments");
        lua_error(lua_state);
    }

    if(!lua_isnumber(lua_state, -1)) {
        /* prints a warning message */
        V_WARNING("Incorrect argument 'expected number'\n");

        /* pushes an error message to Lua */
        lua_pushstring(lua_state, "Incorrect argument to 'expected number'");
        lua_error(lua_state);
    }

    if(!lua_isstring(lua_state, -2)) {
        /* prints a warning message */
        V_WARNING("Incorrect argument 'expected string'\n");

        /* pushes an error message to Lua */
        lua_pushstring(lua_state, "Incorrect argument to 'expected string'");
        lua_error(lua_state);
    }

    if(!lua_islightuserdata(lua_state, -3)) {
        /* prints a warning message */
        V_WARNING("Incorrect argument 'expected lightuserdata'\n");

        /* pushes an error message to Lua */
        lua_pushstring(lua_state, "Incorrect argument 'expected lightuserdata'");
        lua_error(lua_state);
    }

    /* converts the third argument into an integer */
    data_size = lua_tointeger(lua_state, -1);

    /* converts the second argument into a string */
    data = lua_tostring(lua_state, -2);

    /* converts the first argument into HTTP parser structure */
    http_parser = (struct http_parser_t *) lua_touserdata(lua_state, -3);

    /* retrieves the connection from the HTTP parser parameters */
    connection = (struct connection_t *) http_parser->parameters;

    /* allocates the data buffer (in a safe maner) then
    copies the data (from Lua) into the buffer */
    connection->alloc_data(connection, data_size * sizeof(unsigned char), (void **) &buffer);
    memcpy(buffer, data, data_size);

    /* writes the response to the connection */
    connection->write_connection(
        connection,
        buffer,
        data_size,
        _send_response_callback_handler_lua,
        (void *) (size_t) http_parser->flags
    );

    /* return the number of results */
    return 0;
}
コード例 #18
0
ファイル: jive_framework.c プロジェクト: presslab-us/jivelite
static int _draw_screen(lua_State *L) {
	JiveSurface *srf;
	Uint32 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
	clock_t c0 = 0, c1 = 0;
	bool_t standalone_draw, drawn = false;


	JIVEL_STACK_CHECK_BEGIN(L);

	/* stack is:
	 * 1: framework
	 * 2: surface (in screen format)
	 * 3: standalone_draw (used to draw screen to a new surface)
	 */

	srf = *(JiveSurface **)lua_touserdata(L, 2);
	
	standalone_draw = lua_toboolean(L, 3);

	/* Exit if we have no windows, nothing to draw */
	lua_getfield(L, 1, "windowStack");
	if (lua_objlen(L, -1) == 0) {
		lua_pop(L, 2);

		JIVEL_STACK_CHECK_ASSERT(L);
		return 0;
	}
	lua_rawgeti(L, -1, 1);	// topwindow

	if (perfwarn.screen) {
		t0 = jive_jiffies();
		c0 = clock();
	}


	do {
		jive_origin = next_jive_origin;

		/* Layout window and widgets */
		if (jive_getmethod(L, -1, "checkLayout")) {
			lua_pushvalue(L, -2);
			lua_call(L, 1, 0);
		}

		/* check in case the origin changes during layout */
	} while (jive_origin != next_jive_origin);

	if (perfwarn.screen) t1 = jive_jiffies();
 
	/* Widget animations - don't update in a standalone draw as its not the main screen update */
	if (!standalone_draw) {
		lua_getfield(L, 1, "animations");
		lua_pushnil(L);
		while (lua_next(L, -2) != 0) {
			lua_getfield(L, -1, "animations");
			lua_pushnil(L);
			while (lua_next(L, -2) != 0) {
				int frame;
				
				/* stack is:
				 * -2: key
				 * -1: table
				 */
				lua_rawgeti(L, -1, 2);
				frame = lua_tointeger(L, -1) - 1;
				
				if (frame == 0) {
					lua_rawgeti(L, -2, 1); // function
					lua_pushvalue(L, -6); // widget
					lua_call(L, 1, 0);
					// function is poped by lua_call
					
					lua_rawgeti(L, -2, 3);
					lua_rawseti(L, -3, 2);
				}
				else {
				  lua_pushinteger(L, frame);
				  lua_rawseti(L, -3, 2);
				}
				lua_pop(L, 2);
			}
			lua_pop(L, 2);
		}
		lua_pop(L, 1);
	}

	if (perfwarn.screen) t2 = jive_jiffies();

	/* Window transitions */
	lua_getfield(L, 1, "transition");
	if (!lua_isnil(L, -1)) {
		/* Draw background */
		jive_surface_set_clip(srf, NULL);
		jive_tile_set_alpha(jive_background, 0); // no alpha channel
		jive_tile_blit(jive_background, srf, 0, 0, screen_w, screen_h);

		if (perfwarn.screen) t3 = jive_jiffies();
		
		/* Animate screen transition */
		lua_pushvalue(L, -1);
		lua_pushvalue(L, -3);  	// widget
		lua_pushvalue(L, 2);	// surface
		lua_call(L, 2, 0);

		drawn = true;
	}
	else if (jive_dirty_region.w || standalone_draw) {
		SDL_Rect dirty;

		/* only redraw dirty region for non standalone draws */
		if (!standalone_draw) {
			jive_rect_union(&jive_dirty_region, &last_dirty_region, &dirty);
			jive_surface_set_clip(srf, &dirty);
		}

#if 0
		printf("REDRAW: %d,%d %dx%d\n", jive_dirty_region.x, jive_dirty_region.y, jive_dirty_region.w, jive_dirty_region.h);
		printf("--> %d,%d %dx%d\n", dirty.x, dirty.y, dirty.w, dirty.h);
#endif

		/* Draw background */
		jive_tile_blit(jive_background, srf, 0, 0, screen_w, screen_h);

		if (perfwarn.screen) t3 = jive_jiffies();

		/* Draw screen */
		if (jive_getmethod(L, -2, "draw")) {
			lua_pushvalue(L, -3);	// widget
			lua_pushvalue(L, 2);	// surface
			lua_pushinteger(L, JIVE_LAYER_ALL); // layer
			lua_call(L, 3, 0);
		}

#if 0
		// show the dirty region for debug purposes:
		jive_surface_rectangleColor(srf, jive_dirty_region.x, jive_dirty_region.y,
			jive_dirty_region.x + jive_dirty_region.w, jive_dirty_region.y + jive_dirty_region.h, 0xFFFFFFFF);
#endif	

		/* clear the dirty region for non standalone draws */
		if (!standalone_draw) {
			memcpy(&last_dirty_region, &jive_dirty_region, sizeof(last_dirty_region));
			jive_dirty_region.w = 0;
		}

		drawn = true;
	}

	if (perfwarn.screen) {
		t4 = jive_jiffies();
		c1 = clock();
		if (t4-t0 > perfwarn.screen) {
			if (!t3) {
				t3 = t2;
			}
			printf("update_screen > %dms: %4dms (%dms) [layout:%dms animate:%dms background:%dms draw:%dms]\n",
				   perfwarn.screen, t4-t0, (int)((c1-c0) * 1000 / CLOCKS_PER_SEC), t1-t0, t2-t1, t3-t2, t4-t3);
		}
	}
	
	lua_pop(L, 3);

	JIVEL_STACK_CHECK_END(L);

	lua_pushboolean(L, drawn);
	return 1;
}
コード例 #19
0
ファイル: core.c プロジェクト: jakobwesthoff/lucie
static void var_dump( lua_State* L, int depth ) 
{
    // All the different datatypes need to be handled differently
    if ( lua_isnil( L, -1 ) ) 
    {
        print_padded_line( depth, "NIL" );
    }
    else if ( lua_isfunction( L, -1 ) ) 
    {
        print_padded_line( depth, "FUNCTION" );
    }
    else if ( lua_isuserdata( L, -1 ) ) 
    {
        print_padded_line( depth, "USERDATA" );
    }
    else if ( lua_isthread( L, -1 ) ) 
    {
        print_padded_line( depth, "THREAD" );
    }
    else if ( lua_isboolean( L, -1 ) ) 
    {        
        print_padded_line( depth, "boolean(%s)", lua_toboolean( L, -1 ) == true ? "true" : "false" );
    }
    else if ( lua_isnumber( L, -1 ) )
    {
        double number = lua_tonumber( L, -1 );

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

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

    lua_pop( L, 1 );
}
コード例 #20
0
ファイル: jive_framework.c プロジェクト: presslab-us/jivelite
int jiveL_dispatch_event(lua_State *L) {
	Uint32 r = 0;
	Uint32 t0 = 0, t1 = 0;
	clock_t c0 = 0, c1 = 0;

	/* stack is:
	 * 1: framework
	 * 2: widget
	 * 3: event
	 */

	if (perfwarn.event) {
		t0 = jive_jiffies();
		c0 = clock();
	}

	lua_pushcfunction(L, jive_traceback);  /* push traceback function */

	// call global event listeners
	if (jive_getmethod(L, 1, "_event")) {
		lua_pushvalue(L, 1); // framework
		lua_pushvalue(L, 3); // event
		lua_pushboolean(L, 1); // global listeners

		if (lua_pcall(L, 3, 1, 4) != 0) {
			LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1));
			return 0;
		}

		r |= lua_tointeger(L, -1);
		lua_pop(L, 1);
	}

	/* by default send the event to the top window. fetch that top
	 * window here in case the global event handler has modified
	 * the window stack.
	 */
	if (lua_isnil(L, 2)) {
		lua_getfield(L, 1, "windowStack");
		if (lua_objlen(L, -1) == 0) {
			lua_pop(L, 1);
			return 0;
		}
		lua_rawgeti(L, -1, 1);
		lua_replace(L, 2);
	}

	// call widget event handler, unless the event is consumed
	if (!(r & JIVE_EVENT_CONSUME) && jive_getmethod(L, 2, "_event")) {
		lua_pushvalue(L, 2); // widget
		lua_pushvalue(L, 3); // event

		if (lua_pcall(L, 2, 1, 4) != 0) {
			LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1));
			return 0;
		}

		r |= lua_tointeger(L, -1);
		lua_pop(L, 1);
	}

	// call unused event listeners, unless the event is consumed
	if (!(r & JIVE_EVENT_CONSUME) && jive_getmethod(L, 1, "_event")) {
		lua_pushvalue(L, 1); // framework
		lua_pushvalue(L, 3); // event
		lua_pushboolean(L, 0); // unused listeners

		if (lua_pcall(L, 3, 1, 4) != 0) {
			LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1));
			return 0;
		}

		r |= lua_tointeger(L, -1);
		lua_pop(L, 1);
	}

	if (perfwarn.event) {
		t1 = jive_jiffies();
		c1 = clock();
		if (t1-t0 > perfwarn.event) {
			printf("process_event > %dms: %4dms (%dms) ", perfwarn.event, t1-t0, (int)((c1-c0) * 1000 / CLOCKS_PER_SEC));
			lua_getglobal(L, "tostring");
			lua_pushvalue(L, 2);
			lua_call(L, 1, 1);
			lua_pushcfunction(L, jiveL_event_tostring);
			lua_pushvalue(L, 3);
			lua_call(L, 1, 1);
			printf("[widget:%s event:%s]\n", lua_tostring(L, -2), lua_tostring(L, -1));
			lua_pop(L, 2);
		}
	}

	lua_pushinteger(L, r);
	return 1;
}
コード例 #21
0
ファイル: LuaRegManLib.cpp プロジェクト: hjpotter92/PtokaX
static int AddReg(lua_State * L) {
	if(lua_gettop(L) == 3) {
        if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 2) != LUA_TSTRING || lua_type(L, 3) != LUA_TNUMBER) {
            luaL_checktype(L, 1, LUA_TSTRING);
            luaL_checktype(L, 2, LUA_TSTRING);
            luaL_checktype(L, 3, LUA_TNUMBER);
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        size_t szNickLen, szPassLen;
        char *sNick = (char *)lua_tolstring(L, 1, &szNickLen);
        char *sPass = (char *)lua_tolstring(L, 2, &szPassLen);

#if LUA_VERSION_NUM < 503
		uint16_t i16Profile = (uint16_t)lua_tonumber(L, 3);
#else
        uint16_t i16Profile = (uint16_t)lua_tointeger(L, 3);
#endif

        if(i16Profile > clsProfileManager::mPtr->ui16ProfileCount-1 || szNickLen == 0 || szNickLen > 64 || szPassLen == 0 || szPassLen > 64 || strpbrk(sNick, " $|") != NULL || strchr(sPass, '|') != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        bool bAdded = clsRegManager::mPtr->AddNew(sNick, sPass, i16Profile);

        lua_settop(L, 0);

        if(bAdded == false) {
            lua_pushnil(L);
            return 1;
        }

        lua_pushboolean(L, 1);
        return 1;
    } else if(lua_gettop(L) == 2) {
        if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 2) != LUA_TNUMBER) {
            luaL_checktype(L, 1, LUA_TSTRING);
            luaL_checktype(L, 2, LUA_TNUMBER);
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        size_t szNickLen;
        char *sNick = (char *)lua_tolstring(L, 1, &szNickLen);

#if LUA_VERSION_NUM < 503
		uint16_t ui16Profile = (uint16_t)lua_tonumber(L, 2);
#else
        uint16_t ui16Profile = (uint16_t)lua_tointeger(L, 2);
#endif

        if(ui16Profile > clsProfileManager::mPtr->ui16ProfileCount-1 || szNickLen == 0 || szNickLen > 64 || strpbrk(sNick, " $|") != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        // check if user is registered
        if(clsRegManager::mPtr->Find(sNick, szNickLen) != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        User * pUser = clsHashManager::mPtr->FindUser(sNick, szNickLen);
        if(pUser == NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        if(pUser->pLogInOut == NULL) {
            pUser->pLogInOut = new (std::nothrow) LoginLogout();
            if(pUser->pLogInOut == NULL) {
                pUser->ui32BoolBits |= User::BIT_ERROR;
                pUser->Close();

                AppendDebugLog("%s - [MEM] Cannot allocate new pUser->pLogInOut in RegMan.AddReg\n");
                lua_settop(L, 0);
                lua_pushnil(L);
                return 1;
            }
        }

        pUser->SetBuffer(clsProfileManager::mPtr->ppProfilesTable[ui16Profile]->sName);
        pUser->ui32BoolBits |= User::BIT_WAITING_FOR_PASS;

        pUser->SendFormat("RegMan.AddReg", true, "<%s> %s.|$GetPass|", clsSettingManager::mPtr->sPreTexts[clsSettingManager::SETPRETXT_HUB_SEC], clsLanguageManager::mPtr->sTexts[LAN_YOU_WERE_REGISTERED_PLEASE_ENTER_YOUR_PASSWORD]);

        lua_settop(L, 0);
        lua_pushboolean(L, 1);
        return 1;
    } else {
        luaL_error(L, "bad argument count to 'RegMan.AddReg' (2 or 3 expected, got %d)", lua_gettop(L));
        lua_settop(L, 0);
        lua_pushnil(L);
        return 1;
    }
}
コード例 #22
0
static int
ngx_http_lua_ngx_re_gmatch_iterator(lua_State *L)
{
    ngx_http_lua_regex_ctx_t    *ctx;
    ngx_http_request_t          *r;
    int                         *cap;
    ngx_int_t                    rc;
    ngx_uint_t                   n;
    int                          i;
    ngx_str_t                    subj;
    int                          offset;
    const char                  *msg = NULL;

    /* upvalues in order: subj ctx offset */

    subj.data = (u_char *) lua_tolstring(L, lua_upvalueindex(1), &subj.len);
    ctx = (ngx_http_lua_regex_ctx_t *) lua_touserdata(L, lua_upvalueindex(2));
    offset = (int) lua_tointeger(L, lua_upvalueindex(3));

    if (offset < 0) {
        lua_pushnil(L);
        return 1;
    }

    cap = ctx->captures;

    dd("offset %d, r %p, subj %s", (int) offset, ctx->request, subj.data);

    lua_pushlightuserdata(L, &ngx_http_lua_request_key);
    lua_rawget(L, LUA_GLOBALSINDEX);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

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

    if (r != ctx->request || r->pool != ctx->request->pool) {
        return luaL_error(L, "attempt to use ngx.re.gmatch iterator in a "
                "request that did not create it");
    }

    dd("regex exec...");

    if (ctx->flags & NGX_LUA_RE_MODE_DFA) {

#if LUA_HAVE_PCRE_DFA

        int ws[NGX_LUA_RE_DFA_MODE_WORKSPACE_COUNT];

        rc = ngx_http_lua_regex_dfa_exec(ctx->regex, ctx->regex_sd, &subj,
            offset, cap, ctx->captures_len, ws,
            NGX_LUA_RE_DFA_MODE_WORKSPACE_COUNT);

#else /* LUA_HAVE_PCRE_DFA */
        msg = "at least pcre 6.0 is required for the DFA mode";
        goto error;

#endif /* LUA_HAVE_PCRE_DFA */

    } else {
        rc = ngx_http_lua_regex_exec(ctx->regex, ctx->regex_sd, &subj,
                                     offset, cap, ctx->captures_len);
    }

    if (rc == NGX_REGEX_NO_MATCHED) {
        /* set upvalue "offset" to -1 */
        lua_pushinteger(L, -1);
        lua_replace(L, lua_upvalueindex(3));

        if (!(ctx->flags & NGX_LUA_RE_COMPILE_ONCE)) {
            if (ctx->regex_sd) {
                ngx_http_lua_regex_free_study_data(r->pool, ctx->regex_sd);
                ctx->regex_sd = NULL;
            }

            ngx_pfree(r->pool, cap);
        }

        lua_pushnil(L);
        return 1;
    }

    if (rc < 0) {
        msg = lua_pushfstring(L, ngx_regex_exec_n " failed: %d on \"%s\"",
                (int) rc, subj.data);
        goto error;
    }

    if (rc == 0) {
        if (ctx->flags & NGX_LUA_RE_MODE_DFA) {
            rc = 1;

        } else {
            goto error;
        }
    }

    dd("rc = %d", (int) rc);

    lua_createtable(L, rc - 1 /* narr */, 1 /* nrec */);

    for (i = 0, n = 0; i < rc; i++, n += 2) {
        dd("capture %d: %d %d", i, cap[n], cap[n + 1]);
        if (cap[n] < 0) {
            lua_pushnil(L);

        } else {
            lua_pushlstring(L, (char *) &subj.data[cap[n]],
                    cap[n + 1] - cap[n]);

            dd("pushing capture %s at %d", lua_tostring(L, -1), (int) i);
        }

        lua_rawseti(L, -2, (int) i);
    }

    offset = cap[1];
    if (offset == (ssize_t) subj.len) {
        offset = -1;

        if (!(ctx->flags & NGX_LUA_RE_COMPILE_ONCE)) {
            if (ctx->regex_sd) {
                ngx_http_lua_regex_free_study_data(r->pool, ctx->regex_sd);
                ctx->regex_sd = NULL;
            }

            ngx_pfree(r->pool, cap);
        }
    }

    lua_pushinteger(L, offset);
    lua_replace(L, lua_upvalueindex(3));

    return 1;

error:
    lua_pushinteger(L, -1);
    lua_replace(L, lua_upvalueindex(3));

    if (!(ctx->flags & NGX_LUA_RE_COMPILE_ONCE)) {
        if (ctx->regex_sd) {
            ngx_http_lua_regex_free_study_data(r->pool, ctx->regex_sd);
            ctx->regex_sd = NULL;
        }

        ngx_pfree(r->pool, cap);
    }

    return luaL_error(L, msg);
}
コード例 #23
0
inline int VLuaWrapper::getIntParameter (unsigned int iParameter) const
{
    return ((int) (lua_tointeger (mp_State, iParameter + s_ParamOffset)));
}
コード例 #24
0
static int
ngx_http_lua_ngx_re_match(lua_State *L)
{
    /* u_char                      *p; */
    ngx_http_request_t          *r;
    ngx_str_t                    subj;
    ngx_str_t                    pat;
    ngx_str_t                    opts;
    ngx_lua_regex_compile_t      re_comp;
    ngx_http_lua_regex_t        *re;
    const char                  *msg;
    ngx_int_t                    rc;
    ngx_uint_t                   n;
    int                          i;
    ngx_int_t                    pos = 0;
    int                          nargs;
    int                         *cap = NULL;
    int                          ovecsize;
    ngx_uint_t                   flags;
    ngx_pool_t                  *pool, *old_pool;
    ngx_http_lua_main_conf_t    *lmcf = NULL;
    u_char                       errstr[NGX_MAX_CONF_ERRSTR + 1];
    pcre_extra                  *sd = NULL;

    nargs = lua_gettop(L);

    if (nargs != 2 && nargs != 3 && nargs != 4) {
        return luaL_error(L, "expecting two or three or four arguments, "
                "but got %d", nargs);
    }

    lua_pushlightuserdata(L, &ngx_http_lua_request_key);
    lua_rawget(L, LUA_GLOBALSINDEX);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

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

    subj.data = (u_char *) luaL_checklstring(L, 1, &subj.len);
    pat.data = (u_char *) luaL_checklstring(L, 2, &pat.len);

    ngx_memzero(&re_comp, sizeof(ngx_lua_regex_compile_t));

    if (nargs >= 3) {
        opts.data = (u_char *) luaL_checklstring(L, 3, &opts.len);

        if (nargs == 4) {
            luaL_checktype(L, 4, LUA_TTABLE);
            lua_getfield(L, 4, "pos");
            if (lua_isnumber(L, -1)) {
                pos = (ngx_int_t) lua_tointeger(L, -1);
                if (pos < 0) {
                    pos = 0;
                }

            } else if (lua_isnil(L, -1)) {
                pos = 0;

            } else {
                msg = lua_pushfstring(L, "bad pos field type in the ctx table "
                        "argument: %s",
                        luaL_typename(L, -1));

                return luaL_argerror(L, 4, msg);
            }

            lua_pop(L, 1);
        }

    } else {
        opts.data = (u_char *) "";
        opts.len = 0;
    }

    re_comp.options = 0;

    flags = ngx_http_lua_ngx_re_parse_opts(L, &re_comp, &opts, 3);

    if (flags & NGX_LUA_RE_COMPILE_ONCE) {
        lmcf = ngx_http_get_module_main_conf(r, ngx_http_lua_module);
        pool = lmcf->pool;

        dd("server pool %p", lmcf->pool);

        lua_pushlightuserdata(L, &ngx_http_lua_regex_cache_key);
        lua_rawget(L, LUA_REGISTRYINDEX); /* table */

        lua_pushliteral(L, "m");
        lua_pushvalue(L, 2); /* table regex */

        dd("options size: %d", (int) sizeof(re_comp.options));

        lua_pushlstring(L, (char *) &re_comp.options, sizeof(re_comp.options));
                /* table regex opts */

        lua_concat(L, 3); /* table key */
        lua_pushvalue(L, -1); /* table key key */

        dd("regex cache key: %.*s", (int) (pat.len + sizeof(re_comp.options)),
                lua_tostring(L, -1));

        lua_rawget(L, -3); /* table key re */
        re = lua_touserdata(L, -1);

        lua_pop(L, 1); /* table key */

        if (re) {
            ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                    "lua regex cache hit for match regex \"%s\" with "
                    "options \"%s\"", pat.data, opts.data);

            lua_pop(L, 2);

            dd("restoring regex %p, ncaptures %d,  captures %p", re->regex,
                    re->ncaptures, re->captures);

            re_comp.regex = re->regex;
            sd = re->regex_sd;
            re_comp.captures = re->ncaptures;
            cap = re->captures;

            if (flags & NGX_LUA_RE_MODE_DFA) {
                ovecsize = 2;

            } else {
                ovecsize = (re->ncaptures + 1) * 3;
            }

            goto exec;
        }

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "lua regex cache miss for match regex \"%s\" "
                "with options \"%s\"", pat.data, opts.data);

        if (lmcf->regex_cache_entries >= lmcf->regex_cache_max_entries) {

            if (lmcf->regex_cache_entries == lmcf->regex_cache_max_entries) {
                ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
                        "lua exceeding regex cache max entries (%i)",
                        lmcf->regex_cache_max_entries);

                lmcf->regex_cache_entries++;
            }

            pool = r->pool;
            flags &= ~NGX_LUA_RE_COMPILE_ONCE;
        }

    } else {
        pool = r->pool;
    }

    dd("pool %p, r pool %p", pool, r->pool);

    re_comp.pattern = pat;
    re_comp.err.len = NGX_MAX_CONF_ERRSTR;
    re_comp.err.data = errstr;
    re_comp.pool = pool;

    ngx_log_debug5(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
            "lua compiling match regex \"%s\" with options \"%s\" "
            "(compile once: %d) (dfa mode: %d) (jit mode: %d)",
            pat.data, opts.data,
            (flags & NGX_LUA_RE_COMPILE_ONCE) != 0,
            (flags & NGX_LUA_RE_MODE_DFA) != 0,
            (flags & NGX_LUA_RE_MODE_JIT) != 0);

    old_pool = ngx_http_lua_pcre_malloc_init(pool);

    rc = ngx_lua_regex_compile(&re_comp);

    ngx_http_lua_pcre_malloc_done(old_pool);

    if (rc != NGX_OK) {
        dd("compile failed");

        re_comp.err.data[re_comp.err.len] = '\0';
        msg = lua_pushfstring(L, "failed to compile regex \"%s\": %s",
                pat.data, re_comp.err.data);

        return luaL_argerror(L, 2, msg);
    }

#if LUA_HAVE_PCRE_JIT

    if (flags & NGX_LUA_RE_MODE_JIT) {

        old_pool = ngx_http_lua_pcre_malloc_init(pool);

        sd = pcre_study(re_comp.regex, PCRE_STUDY_JIT_COMPILE, &msg);

        ngx_http_lua_pcre_malloc_done(old_pool);

#   if (NGX_DEBUG)
        dd("sd = %p", sd);

        if (msg != NULL) {
            ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "pcre study failed with PCRE_STUDY_JIT_COMPILE: %s (%p)",
                msg, sd);
        }

        if (sd != NULL) {
            int         jitted;

            old_pool = ngx_http_lua_pcre_malloc_init(pool);

            pcre_fullinfo(re_comp.regex, sd, PCRE_INFO_JIT, &jitted);

            ngx_http_lua_pcre_malloc_done(old_pool);

            ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "pcre JIT compiling result: %d", jitted);
        }
#   endif /* NGX_DEBUG */

    } else {
        old_pool = ngx_http_lua_pcre_malloc_init(pool);

        sd = pcre_study(re_comp.regex, 0, &msg);

        ngx_http_lua_pcre_malloc_done(old_pool);

#   if (NGX_DEBUG)
        dd("sd = %p", sd);

        if (msg != NULL) {
            ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "pcre_study failed with PCRE_STUDY_JIT_COMPILE: %s (%p)",
                msg, sd);
        }
#   endif /* NGX_DEBUG */
    }

#else  /* LUA_HAVE_PCRE_JIT */

    if (flags & NGX_LUA_RE_MODE_JIT) {
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "your pcre build does not have JIT support and "
                "the \"j\" regex option is ignored");
    }

#endif /* LUA_HAVE_PCRE_JIT */

    dd("compile done, captures %d", (int) re_comp.captures);

    if (flags & NGX_LUA_RE_MODE_DFA) {
        ovecsize = 2;

    } else {
        ovecsize = (re_comp.captures + 1) * 3;
    }

    dd("allocating cap with size: %d", (int) ovecsize);

    cap = ngx_palloc(pool, ovecsize * sizeof(int));

    if (cap == NULL) {
        flags &= ~NGX_LUA_RE_COMPILE_ONCE;
        msg = "out of memory";
        goto error;
    }

    if (flags & NGX_LUA_RE_COMPILE_ONCE) {

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "lua saving compiled regex (%d captures) into the cache "
                "(entries %i)", re_comp.captures,
                 lmcf ? lmcf->regex_cache_entries : 0);

        re = ngx_palloc(pool, sizeof(ngx_http_lua_regex_t));
        if (re == NULL) {
            return luaL_error(L, "out of memory");
        }

        dd("saving regex %p, ncaptures %d,  captures %p", re_comp.regex,
                re_comp.captures, cap);

        re->regex = re_comp.regex;
        re->regex_sd = sd;
        re->ncaptures = re_comp.captures;
        re->captures = cap;
        re->replace = NULL;

        lua_pushlightuserdata(L, re); /* table key value */
        lua_rawset(L, -3); /* table */
        lua_pop(L, 1);

        if (lmcf) {
            lmcf->regex_cache_entries++;
        }
    }

exec:
    if (flags & NGX_LUA_RE_MODE_DFA) {

#if LUA_HAVE_PCRE_DFA

        int ws[NGX_LUA_RE_DFA_MODE_WORKSPACE_COUNT];
        rc = ngx_http_lua_regex_dfa_exec(re_comp.regex, sd, &subj,
            (int) pos, cap, ovecsize, ws, NGX_LUA_RE_DFA_MODE_WORKSPACE_COUNT);

#else /* LUA_HAVE_PCRE_DFA */

        msg = "at least pcre 6.0 is required for the DFA mode";
        goto error;

#endif /* LUA_HAVE_PCRE_DFA */

    } else {
        rc = ngx_http_lua_regex_exec(re_comp.regex, sd, &subj, (int) pos, cap,
                ovecsize);
    }

    if (rc == NGX_REGEX_NO_MATCHED) {
        ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                "regex \"%s\" not matched on string \"%s\" starting from %z",
                pat.data, subj.data, pos);

        if (!(flags & NGX_LUA_RE_COMPILE_ONCE)) {
            if (sd) {
                ngx_http_lua_regex_free_study_data(pool, sd);
            }

            ngx_pfree(pool, re_comp.regex);
            ngx_pfree(pool, cap);
        }

        lua_pushnil(L);
        return 1;
    }

    if (rc < 0) {
        msg = lua_pushfstring(L, ngx_regex_exec_n " failed: %d on \"%s\" "
            "using \"%s\"", (int) rc, subj.data, pat.data);
        goto error;
    }

    if (rc == 0) {
        if (flags & NGX_LUA_RE_MODE_DFA) {
            rc = 1;

        } else {
            msg = "capture size too small";
            goto error;
        }
    }

    dd("rc = %d", (int) rc);

    lua_createtable(L, rc - 1 /* narr */, 1 /* nrec */);

    for (i = 0, n = 0; i < rc; i++, n += 2) {
        dd("capture %d: %d %d", i, cap[n], cap[n + 1]);
        if (cap[n] < 0) {
            lua_pushnil(L);

        } else {
            lua_pushlstring(L, (char *) &subj.data[cap[n]],
                    cap[n + 1] - cap[n]);

            dd("pushing capture %s at %d", lua_tostring(L, -1), (int) i);
        }

        lua_rawseti(L, -2, (int) i);
    }

    if (nargs == 4) { /* having ctx table */
        pos = cap[1];
        lua_pushinteger(L, (lua_Integer) pos);
        lua_setfield(L, 4, "pos");
    }

    if (!(flags & NGX_LUA_RE_COMPILE_ONCE)) {

        if (sd) {
            ngx_http_lua_regex_free_study_data(pool, sd);
        }

        ngx_pfree(pool, re_comp.regex);
        ngx_pfree(pool, cap);
    }

    return 1;

error:
    if (!(flags & NGX_LUA_RE_COMPILE_ONCE)) {
        if (sd) {
            ngx_http_lua_regex_free_study_data(pool, sd);
        }

        if (re_comp.regex) {
            ngx_pfree(pool, re_comp.regex);
        }

        if (cap) {
            ngx_pfree(pool, cap);
        }
    }

    return luaL_error(L, msg);
}
コード例 #25
0
ファイル: lauxlib.c プロジェクト: monkey0506/lua51src
LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  lua_Integer d = lua_tointeger(L, narg);
  if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
    tag_error(L, narg, LUA_TNUMBER);
  return d;
}
コード例 #26
0
ファイル: cg_luamenu.cpp プロジェクト: Arcadiaprime/japp
	static int Menu_BorderSize( lua_State *L ) {
		menuDef_t *menu = CheckMenu( L, 1 );
		int value = lua_tointeger( L, 2 );
		menu->window.borderSize = value;
		return 0;
	}
コード例 #27
0
static int
ngx_http_lua_socket_udp_setpeername(lua_State *L)
{
    ngx_http_request_t          *r;
    ngx_http_lua_ctx_t          *ctx;
    ngx_str_t                    host;
    int                          port;
    ngx_resolver_ctx_t          *rctx, temp;
    ngx_http_core_loc_conf_t    *clcf;
    int                          saved_top;
    int                          n;
    u_char                      *p;
    size_t                       len;
    ngx_url_t                    url;
    ngx_int_t                    rc;
    ngx_http_lua_loc_conf_t     *llcf;
    ngx_udp_connection_t        *uc;
    int                          timeout;

    ngx_http_lua_socket_udp_upstream_t      *u;

    n = lua_gettop(L);
    if (n != 2 && n != 3) {
        return luaL_error(L, "ngx.socket.udp setpeername: expecting 2 or 3 "
                          "arguments (including the object), but seen %d", n);
    }

    lua_pushlightuserdata(L, &ngx_http_lua_request_key);
    lua_rawget(L, LUA_GLOBALSINDEX);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

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

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

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

    luaL_checktype(L, 1, LUA_TTABLE);

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

    host.data = ngx_palloc(r->pool, len + 1);
    if (host.data == NULL) {
        return luaL_error(L, "out of memory");
    }

    host.len = len;

    ngx_memcpy(host.data, p, len);
    host.data[len] = '\0';

    if (n == 3) {
        port = luaL_checkinteger(L, 3);

        if (port < 0 || port > 65536) {
            lua_pushnil(L);
            lua_pushfstring(L, "bad port number: %d", port);
            return 2;
        }

    } else { /* n == 2 */
        port = 0;
    }

    lua_rawgeti(L, 1, SOCKET_CTX_INDEX);
    u = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (u) {
        if (u->waiting) {
            lua_pushnil(L);
            lua_pushliteral(L, "socket busy");
            return 2;
        }

        if (u->udp_connection.connection) {
            ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "lua udp socket reconnect without shutting down");

            ngx_http_lua_socket_udp_finalize(r, u);
        }

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua reuse socket upstream ctx");

    } else {
        u = lua_newuserdata(L, sizeof(ngx_http_lua_socket_udp_upstream_t));
        if (u == NULL) {
            return luaL_error(L, "out of memory");
        }

#if 1
        lua_createtable(L, 0 /* narr */, 1 /* nrec */); /* metatable */
        lua_pushcfunction(L, ngx_http_lua_socket_udp_upstream_destroy);
        lua_setfield(L, -2, "__gc");
        lua_setmetatable(L, -2);
#endif

        lua_rawseti(L, 1, SOCKET_CTX_INDEX);
    }

    ngx_memzero(u, sizeof(ngx_http_lua_socket_udp_upstream_t));

    u->request = r; /* set the controlling request */
    llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module);

    u->conf = llcf;

    uc = &u->udp_connection;

    uc->log = *r->connection->log;

    dd("lua peer connection log: %p", &uc->log);

    lua_rawgeti(L, 1, SOCKET_TIMEOUT_INDEX);
    timeout = (ngx_int_t) lua_tointeger(L, -1);
    lua_pop(L, 1);

    if (timeout > 0) {
        u->read_timeout = (ngx_msec_t) timeout;

    } else {
        u->read_timeout = u->conf->read_timeout;
    }

    ngx_memzero(&url, sizeof(ngx_url_t));

    url.url.len = host.len;
    url.url.data = host.data;
    url.default_port = port;
    url.no_resolve = 1;

    if (ngx_parse_url(r->pool, &url) != NGX_OK) {
        lua_pushnil(L);

        if (url.err) {
            lua_pushfstring(L, "failed to parse host name \"%s\": %s",
                            host.data, url.err);

        } else {
            lua_pushfstring(L, "failed to parse host name \"%s\"", host.data);
        }

        return 2;
    }

    u->resolved = ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_resolved_t));
    if (u->resolved == NULL) {
        return luaL_error(L, "out of memory");
    }

    if (url.addrs && url.addrs[0].sockaddr) {
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua udp socket network address given directly");

        u->resolved->sockaddr = url.addrs[0].sockaddr;
        u->resolved->socklen = url.addrs[0].socklen;
        u->resolved->naddrs = 1;
        u->resolved->host = url.addrs[0].name;

    } else {
        u->resolved->host = host;
        u->resolved->port = (in_port_t) port;
    }

    if (u->resolved->sockaddr) {
        rc = ngx_http_lua_socket_resolve_retval_handler(r, u, L);
        if (rc == NGX_AGAIN) {
            return lua_yield(L, 0);
        }

        return rc;
    }

    clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

    temp.name = host;
    rctx = ngx_resolve_start(clcf->resolver, &temp);
    if (rctx == NULL) {
        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;
        lua_pushnil(L);
        lua_pushliteral(L, "failed to start the resolver");
        return 2;
    }

    if (rctx == NGX_NO_RESOLVER) {
        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;
        lua_pushnil(L);
        lua_pushfstring(L, "no resolver defined to resolve \"%s\"", host.data);
        return 2;
    }

    rctx->name = host;
    rctx->type = NGX_RESOLVE_A;
    rctx->handler = ngx_http_lua_socket_resolve_handler;
    rctx->data = u;
    rctx->timeout = clcf->resolver_timeout;

    u->resolved->ctx = rctx;

    saved_top = lua_gettop(L);

    if (ngx_resolve_name(rctx) != NGX_OK) {
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua udp socket fail to run resolver immediately");

        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;

        u->resolved->ctx = NULL;
        lua_pushnil(L);
        lua_pushfstring(L, "%s could not be resolved", host.data);

        return 2;
    }

    if (u->waiting == 1) {
        /* resolved and already connecting */
        return lua_yield(L, 0);
    }

    n = lua_gettop(L) - saved_top;
    if (n) {
        /* errors occurred during resolving or connecting
         * or already connected */
        return n;
    }

    /* still resolving */

    u->waiting = 1;
    u->prepare_retvals = ngx_http_lua_socket_resolve_retval_handler;

    ctx->data = u;
    ctx->udp_socket_busy = 1;
    ctx->udp_socket_ready = 0;

    if (ctx->entered_content_phase) {
        r->write_event_handler = ngx_http_lua_content_wev_handler;
    }

    return lua_yield(L, 0);
}
コード例 #28
0
ファイル: lqt_common.cpp プロジェクト: iazzi/lqt
int * lqtL_tointref (lua_State *L, int index) {
    int tmp = lua_tointeger(L, index);
    int *ret = (int*)lqtL_getref(L, sizeof(int), false);
    *ret = tmp;
    return ret;
}
コード例 #29
0
static int flipCard (lua_State* L)
{
	ActiveDuel->flipCardForPlayer(lua_tointeger(L, 1), lua_tointeger(L, 2));
	return 0;
}
コード例 #30
0
ファイル: barrier_api.cpp プロジェクト: jorikvdwerf/Tortuga
static int setInstance(lua_State* L) {
	BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
	barrier->SetInstanceIndex(lua_tointeger(L, 2));
	return 0;
}