Exemple #1
0
/***
 * @function rspamd_tcp.request({params})
 * This function creates and sends TCP request to the specified host and port,
 * resolves hostname (if needed) and invokes continuation callback upon data received
 * from the remote peer. This function accepts table of arguments with the following
 * attributes
 *
 * - `task`: rspamd task objects (implies `pool`, `session`, `ev_base` and `resolver` arguments)
 * - `ev_base`: event base (if no task specified)
 * - `resolver`: DNS resolver (no task)
 * - `session`: events session (no task)
 * - `pool`: memory pool (no task)
 * - `host`: IP or name of the peer (required)
 * - `port`: remote port to use (required)
 * - `data`: a table of strings or `rspamd_text` objects that contains data pieces
 * - `callback`: continuation function (required)
 * - `timeout`: floating point value that specifies timeout for IO operations in seconds
 * - `partial`: boolean flag that specifies that callback should be called on any data portion received
 * - `stop_pattern`: stop reading on finding a certain pattern (e.g. \r\n.\r\n for smtp)
 * @return {boolean} true if request has been sent
 */
static gint
lua_tcp_request (lua_State *L)
{
	const gchar *host;
	gchar *stop_pattern = NULL;
	guint port;
	gint cbref, tp;
	struct event_base *ev_base;
	struct lua_tcp_cbdata *cbd;
	struct rspamd_dns_resolver *resolver;
	struct rspamd_async_session *session;
	struct rspamd_task *task = NULL;
	rspamd_mempool_t *pool;
	struct iovec *iov = NULL;
	guint niov = 0, total_out;
	gdouble timeout = default_tcp_timeout;
	gboolean partial = FALSE, do_shutdown = FALSE;

	if (lua_type (L, 1) == LUA_TTABLE) {
		lua_pushstring (L, "host");
		lua_gettable (L, -2);
		host = luaL_checkstring (L, -1);
		lua_pop (L, 1);

		lua_pushstring (L, "port");
		lua_gettable (L, -2);
		port = luaL_checknumber (L, -1);
		lua_pop (L, 1);

		lua_pushstring (L, "callback");
		lua_gettable (L, -2);
		if (host == NULL || lua_type (L, -1) != LUA_TFUNCTION) {
			lua_pop (L, 1);
			msg_err ("tcp request has bad params");
			lua_pushboolean (L, FALSE);
			return 1;
		}
		cbref = luaL_ref (L, LUA_REGISTRYINDEX);

		lua_pushstring (L, "task");
		lua_gettable (L, -2);
		if (lua_type (L, -1) == LUA_TUSERDATA) {
			task = lua_check_task (L, -1);
			ev_base = task->ev_base;
			resolver = task->resolver;
			session = task->s;
			pool = task->task_pool;
		}
		lua_pop (L, 1);

		if (task == NULL) {
			lua_pushstring (L, "ev_base");
			lua_gettable (L, -2);
			if (luaL_checkudata (L, -1, "rspamd{ev_base}")) {
				ev_base = *(struct event_base **)lua_touserdata (L, -1);
			}
			else {
				ev_base = NULL;
			}
			lua_pop (L, 1);

			lua_pushstring (L, "pool");
			lua_gettable (L, -2);
			if (luaL_checkudata (L, -1, "rspamd{mempool}")) {
				pool = *(rspamd_mempool_t **)lua_touserdata (L, -1);
			}
			else {
				pool = NULL;
			}
			lua_pop (L, 1);

			lua_pushstring (L, "resolver");
			lua_gettable (L, -2);
			if (luaL_checkudata (L, -1, "rspamd{resolver}")) {
				resolver = *(struct rspamd_dns_resolver **)lua_touserdata (L, -1);
			}
			else {
				resolver = lua_tcp_global_resolver (ev_base);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "session");
			lua_gettable (L, -2);
			if (luaL_checkudata (L, -1, "rspamd{session}")) {
				session = *(struct rspamd_async_session **)lua_touserdata (L, -1);
			}
			else {
				session = NULL;
			}
			lua_pop (L, 1);
		}

		lua_pushstring (L, "timeout");
		lua_gettable (L, -2);
		if (lua_type (L, -1) == LUA_TNUMBER) {
			timeout = lua_tonumber (L, -1) * 1000.;
		}
		lua_pop (L, 1);

		lua_pushstring (L, "stop_pattern");
		lua_gettable (L, -2);
		if (lua_type (L, -1) == LUA_TSTRING) {
			stop_pattern = rspamd_mempool_strdup (pool, lua_tostring (L, -1));
		}
		lua_pop (L, 1);

		lua_pushstring (L, "partial");
		lua_gettable (L, -2);
		if (lua_type (L, -1) == LUA_TBOOLEAN) {
			partial = lua_toboolean (L, -1);
		}
		lua_pop (L, 1);

		lua_pushstring (L, "shutdown");
		lua_gettable (L, -2);
		if (lua_type (L, -1) == LUA_TBOOLEAN) {
			do_shutdown = lua_toboolean (L, -1);
		}
		lua_pop (L, 1);

		if (pool == NULL) {
			lua_pop (L, 1);
			msg_err ("tcp request has no memory pool associated");
			lua_pushboolean (L, FALSE);
			return 1;
		}

		lua_pushstring (L, "data");
		lua_gettable (L, -2);
		total_out = 0;

		tp = lua_type (L, -1);
		if (tp == LUA_TSTRING || tp == LUA_TUSERDATA) {
			iov = rspamd_mempool_alloc (pool, sizeof (*iov));
			niov = 1;

			if (!lua_tcp_arg_toiovec (L, -1, pool, iov)) {
				lua_pop (L, 1);
				msg_err ("tcp request has bad data argument");
				lua_pushboolean (L, FALSE);
				return 1;
			}

			total_out = iov[0].iov_len;
		}
		else if (tp == LUA_TTABLE) {
			/* Count parts */
			lua_pushnil (L);
			while (lua_next (L, -2) != 0) {
				niov ++;
				lua_pop (L, 1);
			}

			iov = rspamd_mempool_alloc (pool, sizeof (*iov) * niov);
			lua_pushnil (L);
			niov = 0;

			while (lua_next (L, -2) != 0) {
				if (!lua_tcp_arg_toiovec (L, -1, pool, &iov[niov])) {
					lua_pop (L, 2);
					msg_err ("tcp request has bad data argument at pos %d", niov);
					lua_pushboolean (L, FALSE);
					return 1;
				}

				total_out += iov[niov].iov_len;
				niov ++;

				lua_pop (L, 1);
			}
		}

		lua_pop (L, 1);
	}
	else {
		msg_err ("tcp request has bad params");
		lua_pushboolean (L, FALSE);

		return 1;
	}

	cbd = g_slice_alloc0 (sizeof (*cbd));
	cbd->L = L;
	cbd->cbref = cbref;
	cbd->ev_base = ev_base;
	msec_to_tv (timeout, &cbd->tv);
	cbd->fd = -1;
	cbd->pool = pool;
	cbd->partial = partial;
	cbd->do_shutdown = do_shutdown;
	cbd->iov = iov;
	cbd->iovlen = niov;
	cbd->total = total_out;
	cbd->pos = 0;
	cbd->port = port;
	cbd->stop_pattern = stop_pattern;

	if (session) {
		cbd->session = session;
		rspamd_session_add_event (session,
				(event_finalizer_t)lua_tcp_fin,
				cbd,
				g_quark_from_static_string ("lua tcp"));
		cbd->w = rspamd_session_get_watcher (session);
		rspamd_session_watcher_push (session);
	}

	if (rspamd_parse_inet_address (&cbd->addr, host, 0)) {
		rspamd_inet_address_set_port (cbd->addr, port);
		/* Host is numeric IP, no need to resolve */
		if (!lua_tcp_make_connection (cbd)) {
			lua_tcp_maybe_free (cbd);
			lua_pushboolean (L, FALSE);

			return 1;
		}
	}
	else {
		if (task == NULL) {
			if (!make_dns_request (resolver, session, NULL, lua_tcp_dns_handler, cbd,
					RDNS_REQUEST_A, host)) {
				lua_tcp_push_error (cbd, "cannot resolve host: %s", host);
				lua_tcp_maybe_free (cbd);
			}
		}
		else {
			if (!make_dns_request_task (task, lua_tcp_dns_handler, cbd,
					RDNS_REQUEST_A, host)) {
				lua_tcp_push_error (cbd, "cannot resolve host: %s", host);
				lua_tcp_maybe_free (cbd);
			}
		}
	}

	lua_pushboolean (L, TRUE);
	return 1;
}
Exemple #2
0
					font = f;
				}
			}
			if (!font) {
				font = g_resourceloader->loadFont(str);
			}

			textObject->setFont(font);
		} else if (lua_isuserdata(keyObj) && lua_tag(keyObj) == MKTAG('F','O','N','T')) {
			textObject->setFont(getfont(keyObj));
		}
	}

	lua_pushobject(tableObj);
	lua_pushobject(lua_getref(refTextObjectWidth));
	keyObj = lua_gettable();
	if (keyObj) {
		if (lua_isnumber(keyObj)) {
			textObject->setWidth((int)lua_getnumber(keyObj));
		}
	}

	lua_pushobject(tableObj);
	lua_pushobject(lua_getref(refTextObjectHeight));
	keyObj = lua_gettable();
	if (keyObj) {
		if (lua_isnumber(keyObj)) {
			textObject->setHeight((int)lua_getnumber(keyObj));
		}
	}
Exemple #3
0
void ScriptUtil::registerClass(const char* name, const luaL_Reg* members, lua_CFunction newFunction, 
    lua_CFunction deleteFunction, const luaL_Reg* statics,  const std::vector<std::string>& scopePath)
{
    ScriptController* sc = Game::getInstance()->getScriptController();

    // If the type is an inner type, get the correct parent 
    // table on the stack before creating the table for the class.
    if (!scopePath.empty())
    {
        std::string tablename = name;

        // Strip off the scope path part of the name.
        lua_getglobal(sc->_lua, scopePath[0].c_str());
        std::size_t index = tablename.find(scopePath[0]);
        if (index != std::string::npos)
            tablename = tablename.substr(index + scopePath[0].size());
        
        for (unsigned int i = 1; i < scopePath.size(); i++)
        {
            lua_pushstring(sc->_lua, scopePath[i].c_str());
            lua_gettable(sc->_lua, -2);

            index = tablename.find(scopePath[i]);
            if (index != std::string::npos)
                tablename = tablename.substr(index + scopePath[i].size());
        }

        lua_pushstring(sc->_lua, tablename.c_str());
        lua_newtable(sc->_lua);
    }
    else
    {
        // If the type is not an inner type, set it as a global table.
        lua_newtable(sc->_lua);
        lua_pushvalue(sc->_lua, -1);
        lua_setglobal(sc->_lua, name);
    }
    
    // Create the metatable and populate it with the member functions.
    lua_pushliteral(sc->_lua, "__metatable");
    luaL_newmetatable(sc->_lua, name);
    if (members)
        luaL_setfuncs(sc->_lua, members, 0);
    lua_pushstring(sc->_lua, "__index");
    lua_pushvalue(sc->_lua, -2);
    lua_settable(sc->_lua, -3);

    // Add the delete function if it was specified.
    if (deleteFunction)
    {
        lua_pushstring(sc->_lua, "__gc");
        lua_pushcfunction(sc->_lua, deleteFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the metatable on the main table.
    lua_settable(sc->_lua, -3);
    
    // Populate the main table with the static functions.
    if (statics)
        luaL_setfuncs(sc->_lua, statics, 0);

    // Set the new function(s) for the class.
    if (newFunction)
    {
        lua_pushliteral(sc->_lua, "new");
        lua_pushcfunction(sc->_lua, newFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the table we just created within the correct parent table.
    if (!scopePath.empty())
    {
        lua_settable(sc->_lua, -3);

        // Pop all the parent tables off the stack.
        int size = (int)scopePath.size();
        lua_pop(sc->_lua, size);
    }
    else
    {
        // Pop the main table off the stack.
        lua_pop(sc->_lua, 1);
    }
}
bool luaval_to_ccluavaluemap(lua_State* L, int lo, LuaValueDict* ret, const char* funcName)
{
    if ( nullptr == L || nullptr == ret)
        return false;

    tolua_Error tolua_err;
    bool ok = true;
    if (!tolua_istable(L, lo, 0, &tolua_err))
    {
#if COCOS2D_DEBUG >=1
        // luaval_to_native_err(L,"#ferror:",&tolua_err);
#endif
        ok = false;
    }

    if (ok)
    {
        std::string stringKey = "";
        std::string stringValue = "";
        bool boolVal = false;
        LuaValueDict& dict = *ret;
        lua_pushnil(L);                                             /* first key L: lotable ..... nil */
        while ( 0 != lua_next(L, lo ) )                             /* L: lotable ..... key value */
        {
            if (!lua_isstring(L, -2))
            {
                lua_pop(L, 1);                                      /* removes 'value'; keep 'key' for next iteration*/
                continue;
            }

            if(luaval_to_std_string(L, -2, &stringKey))
            {

                if(lua_istable(L, -1))
                {
                    lua_pushnumber(L,1);
                    lua_gettable(L,-2);

                    if (lua_isnil(L, -1) )                          /** if table[1] = nil,we don't think it is a pure array */
                    {
                        lua_pop(L,1);
                        LuaValueDict dictVal;
                        if (luaval_to_ccluavaluemap(L, lua_gettop(L), &dictVal))
                        {
                            dict[stringKey] = LuaValue::dictValue(dictVal);
                        }
                    }
                    else
                    {
                        lua_pop(L,1);
                        LuaValueArray arrVal;
                        if (luaval_to_ccluavaluevector(L, lua_gettop(L), &arrVal))
                        {
                            dict[stringKey] = LuaValue::arrayValue(arrVal);
                        }
                    }
                }
                else if(lua_type(L, -1) == LUA_TSTRING)
                {
                    if(luaval_to_std_string(L, -1, &stringValue))
                    {
                        dict[stringKey] = LuaValue::stringValue(stringValue);
                    }
                }
                else if(lua_type(L, -1) == LUA_TBOOLEAN)
                {
                    if (luaval_to_boolean(L, -1, &boolVal))
                    {
                        dict[stringKey] = LuaValue::booleanValue(boolVal);
                    }
                }
                else if(lua_type(L, -1) == LUA_TNUMBER)
                {
                    dict[stringKey] = LuaValue::floatValue(tolua_tonumber(L, -1, 0));
                }
                else
                {
                    //                    CCASSERT(false, "not supported type");
                }
            }

            lua_pop(L, 1);                                          /* L: lotable ..... key */
        }
    }

    return ok;
}
Exemple #5
0
Layouts* layouts_init(struct dynvSystem* params){

	lua_State* L = static_cast<lua_State*>(dynv_get_pointer_wdc(params, "lua_State", 0));
	if (L == NULL) return 0;

	Layouts *layouts = new Layouts;
	layouts->L = L;

	int status;
	int stack_top = lua_gettop(L);
	lua_getglobal(L, "gpick");
	int gpick_namespace = lua_gettop(L);
	if (lua_type(L, -1)!=LUA_TNIL){

		lua_pushstring(L, "layouts");
		lua_gettable(L, gpick_namespace);
		int layouts_table = lua_gettop(L);

		lua_pushstring(L, "layouts_get");
		lua_gettable(L, gpick_namespace);
		if (lua_type(L, -1) != LUA_TNIL){

			if ((status=lua_pcall(L, 0, 1, 0))==0){
				if (lua_type(L, -1)==LUA_TTABLE){
					int table_index = lua_gettop(L);

					for (int i=1;;i++){
						lua_pushinteger(L, i);
						lua_gettable(L, table_index);
						if (lua_isnil(L, -1)) break;

						lua_pushstring(L, lua_tostring(L, -1));		//duplicate, because lua_gettable replaces stack top
						lua_gettable(L, layouts_table);

						lua_pushstring(L, "human_readable");
						lua_gettable(L, -2);

						lua_pushstring(L, "mask");
						lua_gettable(L, -3);

						Layout *layout = new Layout;
						layout->human_readable = g_strdup(lua_tostring(L, -2));
						layout->name = g_strdup(lua_tostring(L, -4));
						layout->mask = lua_tointeger(L, -1);
						layouts->layouts[layout->name] = layout;

						layouts->all_layouts.push_back(layout);

						//cout<<layout->name<<endl;

						lua_pop(L, 3);
					}

				}
			}else{
				cerr<<"layouts_get: "<<lua_tostring (L, -1)<<endl;
			}
		}
	}
	lua_settop(L, stack_top);

	dynv_set_pointer(params, "Layouts", layouts);

	return layouts;
}
Exemple #6
0
value ml_lua_modinfo (value string) 
{
	CAMLparam1 (string);
	CAMLlocal4 (name, version, depends, tuple);
	int err, i, n;

	lua_State *L = luaL_newstate();
	luaL_openlibs(L);
	err = luaL_dostring (L, String_val(string));
	if (err != 0) {
		caml_failwith("Lua.modinfo");
	}

	name = caml_alloc_string(0);
	version = caml_alloc_string(0);
	depends = caml_alloc_tuple(0);

	lua_pushnil(L);
	while (lua_next(L, -2) != 0) {
		const char *s = lua_tostring(L, -2);

		// Get name string
		if (strcasecmp(s, "name") == 0) { 
			const char *s = lua_tostring(L, -1);
			name = caml_copy_string(s);
		}

		// Get depends array
		else if (strcasecmp(s, "depend") == 0) {
			lua_pushstring(L, "table");
			lua_gettable(L, LUA_GLOBALSINDEX);

			lua_pushstring(L, "getn");
			lua_gettable(L, -2);

			lua_pushvalue(L, -3);
			lua_call(L, 1, 1);
			n = lua_tonumber(L, -1);
			lua_pop(L, 2);

			depends = caml_alloc_tuple(n);

			i = 0;	
			lua_pushnil(L);
			while (lua_next(L, -2) != 0) {
				const char *s = lua_tostring(L, -1);
				Store_field(depends, i, caml_copy_string(s));
				i++;
				lua_pop(L, 1);
			}
		}

		// Get version string
		else if (strcasecmp(s, "version") == 0) {
			const char *s = lua_tostring(L, -1);
			version = caml_copy_string(s);
		}

		lua_pop(L, 1);
	}

	tuple = caml_alloc_tuple(3);
	Store_field(tuple, 0, name);
	Store_field(tuple, 1, version);
	Store_field(tuple, 2, depends);

	CAMLreturn (tuple);
}
Exemple #7
0
int luaNode__index( lua_State* l ) {
    is::Node* node = lua_tonode(l,1);
    if ( node == NULL ) {
        lua_Debug ar1;
        lua_getstack( l, 1, &ar1 );
        lua_getinfo( l, "fl", &ar1 );
        lua_Debug ar2;
        lua_getinfo( l, ">S", &ar2 );
        lua_pushfstring( l, "%s:%d: attempt to index a NULL Node!", ar2.short_src, ar1.currentline );
        return lua_error( l );
    }
    std::string field = luaL_checkstring(l,2);
    if ( field == "pos" ) {
        lua_pushvector( l, node->getPos() );
        return 1;
    } else if ( field == "ang" ) {
        lua_pushvector( l, node->getAng() );
        return 1;
    } else if ( field == "scale" ) {
        lua_pushvector( l, node->getScale() );
        return 1;
    } else if ( field == "color" ) {
        lua_pushcolor( l, node->getColor() );
        return 1;
    } else if ( field == "x" ) {
        lua_pushnumber( l, node->getPos().x );
        return 1;
    } else if ( field == "y" ) {
        lua_pushnumber( l, node->getPos().y );
        return 1;
    } else if ( field == "z" ) {
        lua_pushnumber( l, node->getPos().z );
        return 1;
    } else if ( field == "sx" ) {
        lua_pushnumber( l, node->getScale().x );
        return 1;
    } else if ( field == "sy" ) {
        lua_pushnumber( l, node->getScale().y );
        return 1;
    } else if ( field == "sz" ) {
        lua_pushnumber( l, node->getScale().z );
        return 1;
    } else if ( field == "r" ) {
        lua_pushnumber( l, node->getColor().x );
        return 1;
    } else if ( field == "g" ) {
        lua_pushnumber( l, node->getColor().y );
        return 1;
    } else if ( field == "b" ) {
        lua_pushnumber( l, node->getColor().z );
        return 1;
    } else if ( field == "a" ) {
        lua_pushnumber( l, node->getColor().w );
        return 1;
    }
    if ( luaText__index( l ) ) {
        return 1;
    }
    if ( luaButton__index( l ) ) {
        return 1;
    }
    if ( luaCheckbox__index( l ) ) {
        return 1;
    }
    if ( luaDropdown__index( l ) ) {
        return 1;
    }
    lua_getmetatable( l, 1 );
    lua_pushvalue( l, 2 );
    lua_gettable( l, -2 );
    if ( lua_isnil( l, -1 ) ) {
        lua_pop( l, 1 );
        lua_rawgeti( l, LUA_REGISTRYINDEX, node->m_luaReference );
        lua_pushvalue( l, 2 );
        lua_gettable( l, -2 );
    }
    return 1;
}
Exemple #8
0
static int l_str_reload_actual(lua_State *L)
{
    // Reload a single string proxy
    // Stack: reload_cache proxy_to_reload <top

    // Mark string as reloaded
    lua_pushvalue(L, 2);
    lua_pushvalue(L, 2);
    lua_settable(L, 1);

    // Pull instructions out of the environment and remake value
    lua_getfenv(L, 2);
    bool bIsIndexOperation = false;
    int iCount = (int)lua_objlen(L, 3);
    aux_push_weak_table(L, 0);
    lua_pushvalue(L, 2);
    if(iCount != 0)
    {
        // Fetch reconstruction information, reloading any de-proxying any
        // string proxies which we come across. Also replace any references
        // to the root with the new root.
        lua_checkstack(L, iCount + 1);
        for(int i = 1; i <= iCount; ++i)
        {
            lua_rawgeti(L, 3, i);
            if(lua_type(L, -1) == LUA_TUSERDATA)
            {
                if(i == 1)
                    bIsIndexOperation = true;
                lua_gettable(L, 1); // reload / change root
                lua_pushvalue(L, -1);
                lua_rawseti(L, 3, i);
                lua_rawget(L, 4); // de-proxy
            }
        }

        if(iCount == 2 && bIsIndexOperation)
        {
            // If there were two values, and the first was a proxy, then the
            // instruction is to perform a table lookup.
            lua_gettable(L, -2);
            lua_replace(L, -2);
        }
        else
        {
            // Otherwise, the first value was a method or method name.
            if(lua_type(L, 6) != LUA_TFUNCTION)
            {
                lua_pushvalue(L, 6);
                lua_gettable(L, 7);
                lua_replace(L, 6);
            }
            lua_call(L, iCount - 1, 1);
        }
    }
    else
    {
        // Root object
        lua_settop(L, 2);
        return 1;
    }
    // Update value
    lua_rawset(L, -3);
    lua_pop(L, 2);
    return 1;
}
nzLuaType NzLuaInstance::GetTable(int index) const
{
	return FromLuaType(lua_gettable(m_state, index));
}
Exemple #10
0
static int Image (lua_State * L)
{
  int w, h, c, num_colors;
  unsigned char *pixels;
  Ihandle* ih;
  char str[20];

  if (lua_istable(L, 1))
  {
    int i, j;

    /* get the number of lines */
    h = iuplua_getn(L, 1);  

    /* get the number of columns of the first line */
    lua_pushinteger(L, 1);
    lua_gettable(L, 1);
    w = iuplua_getn(L, -1);  
    lua_pop(L, 1);
    
    pixels = (unsigned char *) malloc (h*w);

    for (i=1; i<=h; i++)
    {
      lua_pushinteger(L, i);
      lua_gettable(L, 1);
      for (j=1; j<=w; j++)
      {
        int idx = (i-1)*w+(j-1);
        lua_pushinteger(L, j);
        lua_gettable(L, -2);
        pixels[idx] = (unsigned char)lua_tointeger(L, -1);
        lua_pop(L, 1);
      }
      lua_pop(L, 1);
    }
    
    ih = IupImage(w,h,pixels);  
    free(pixels);

    num_colors = iuplua_getn(L, 2);
    num_colors = num_colors>255? 255: num_colors;
    for(c=1; c<=num_colors; c++)
    {
      lua_rawgeti(L, 2, c);
      sprintf(str, "%d", c);
      IupStoreAttribute(ih, str, lua_tostring(L,-1));
      lua_pop(L, 1);
    }
  }
  else
  {
    w = (int)luaL_checkinteger(L, 1);
    h = (int)luaL_checkinteger(L, 2);
    pixels = iuplua_checkuchar_array(L, 3, w*h);
    ih = IupImage(w, h, pixels);
    free(pixels);

    num_colors = iuplua_getn(L, 4);
    num_colors = num_colors>256? 256: num_colors;
    for(c=1; c<=num_colors; c++)
    {
      lua_rawgeti(L, 4, c);
      sprintf(str, "%d", c-1);
      IupStoreAttribute(ih, str, lua_tostring(L,-1));
      lua_pop(L, 1);
    }
  }

  iuplua_plugstate(L, ih);
  iuplua_pushihandle_raw(L, ih);
  return 1;
} 
Exemple #11
0
// __depersist metamethod handler
static int l_str_depersist(lua_State *L)
{
    lua_settop(L, 2);
    lua_insert(L, 1);
    LuaPersistReader *pReader = (LuaPersistReader*)lua_touserdata(L, 1);

    // Read the instructions for re-creating the value
    if(!pReader->readStackObject())
        return 0;
    if(lua_type(L, 3) == LUA_TBOOLEAN && lua_toboolean(L, 3) == 1)
    {
        // The current code uses a boolean marker to indicate that the
        // instructions were stored in the environment. Replace the marker
        // with them.
        lua_getfenv(L, 2);
        lua_replace(L, 3);
    }
    else
    {
        // Older versions of the code wrote the instructions here, or nil for
        // no instructions. Convert nil to the empty table, and store the
        // instructions as the userdata's environment.
        if(lua_type(L, 3) == LUA_TNIL)
        {
            lua_newtable(L);
            lua_replace(L, 3);
        }
        lua_pushvalue(L, 3);
        lua_setfenv(L, 2);
    }

    // Prepare t, k for saving the value
    aux_push_weak_table(L, 0);
    lua_pushvalue(L, 2);

    if(lua_objlen(L, 3) == 0)
    {
        // No instructions provided, so read the value itself
        if(!pReader->readStackObject())
            return 0;
    }
    else
    {
        // The instructions are a table of values; unpack them and replace
        // proxies with their values.
        bool bIsIndexOperation = false;
        int iCount = (int)lua_objlen(L, 3);
        lua_checkstack(L, iCount + 1);
        for(int i = 1; i <= iCount; ++i)
        {
            lua_rawgeti(L, 3, i);
            if(lua_type(L, -1) == LUA_TUSERDATA)
            {
                if(i == 1)
                    bIsIndexOperation = true;
                lua_rawget(L, 4);
            }
        }

        if(iCount == 2 && bIsIndexOperation)
        {
            // If there were two values, and the first was a proxy, then the
            // instruction is to perform a table lookup.
            lua_gettable(L, -2);
            lua_replace(L, -2);
        }
        else
        {
            // Otherwise, the first value was a method or method name.
            if(lua_type(L, 6) != LUA_TFUNCTION)
            {
                lua_pushvalue(L, 6);
                lua_gettable(L, 7);
                lua_replace(L, 6);
            }
            lua_call(L, iCount - 1, 1);
        }
    }

    // Save the value
    lua_rawset(L, 4);
    return 0;
}
Exemple #12
0
/* Top-level delegating persist function
 */
static void persist(PersistInfo *pi)
{
					/* perms reftbl ... obj */
	lua_checkstack(pi->L, 2);
	/* If the object has already been written, write a reference to it */
	lua_pushvalue(pi->L, -1);
					/* perms reftbl ... obj obj */
	lua_rawget(pi->L, 2);
					/* perms reftbl ... obj ref? */
	if(!lua_isnil(pi->L, -1)) {
					/* perms reftbl ... obj ref */
		int zero = 0;
		int ref = (intptr_t)lua_touserdata(pi->L, -1);
		pi->writer(pi->L, &zero, sizeof(int), pi->ud);
		pi->writer(pi->L, &ref, sizeof(int), pi->ud);
		lua_pop(pi->L, 1);
					/* perms reftbl ... obj ref */
#ifdef PLUTO_DEBUG
		printindent(pi->level);
		printf("0 %d\n", ref);
#endif
		return;
	}
					/* perms reftbl ... obj nil */
	lua_pop(pi->L, 1);
					/* perms reftbl ... obj */
	/* If the object is nil, write the pseudoreference 0 */
	if(lua_isnil(pi->L, -1)) {
		int zero = 0;
		/* firsttime */
		pi->writer(pi->L, &zero, sizeof(int), pi->ud);
		/* ref */
		pi->writer(pi->L, &zero, sizeof(int), pi->ud);
#ifdef PLUTO_DEBUG
		printindent(pi->level);
		printf("0 0\n");
#endif
		return;
	}
	{
		/* indicate that it's the first time */
		int one = 1;
		pi->writer(pi->L, &one, sizeof(int), pi->ud);
	}
	lua_pushvalue(pi->L, -1);
					/* perms reftbl ... obj obj */
	lua_pushlightuserdata(pi->L, (void*)((intptr_t) ++(pi->counter)));
					/* perms reftbl ... obj obj ref */
	lua_rawset(pi->L, 2);
					/* perms reftbl ... obj */

	pi->writer(pi->L, &pi->counter, sizeof(int), pi->ud);


	/* At this point, we'll give the permanents table a chance to play. */
	{
		lua_pushvalue(pi->L, -1);
					/* perms reftbl ... obj obj */
		lua_gettable(pi->L, 1);
					/* perms reftbl ... obj permkey? */
		if(!lua_isnil(pi->L, -1)) {
					/* perms reftbl ... obj permkey */
			int type = PLUTO_TPERMANENT;
#ifdef PLUTO_DEBUG
			printindent(pi->level);
			printf("1 %d PERM\n", pi->counter);
			pi->level++;
#endif
			pi->writer(pi->L, &type, sizeof(int), pi->ud);
			persist(pi);
			lua_pop(pi->L, 1);
					/* perms reftbl ... obj */
#ifdef PLUTO_DEBUG
			pi->level--;
#endif
			return;
		} else {
					/* perms reftbl ... obj nil */
			lua_pop(pi->L, 1);
					/* perms reftbl ... obj */
		}
					/* perms reftbl ... obj */
	}
	{
		int type = lua_type(pi->L, -1);
		pi->writer(pi->L, &type, sizeof(int), pi->ud);

#ifdef PLUTO_DEBUG
		printindent(pi->level);
		printf("1 %d %d\n", pi->counter, type);
		pi->level++;
#endif
	}

	switch(lua_type(pi->L, -1)) {
		case LUA_TBOOLEAN:
			persistboolean(pi);
			break;
		case LUA_TLIGHTUSERDATA:
			persistlightuserdata(pi);
			break;
		case LUA_TNUMBER:
			persistnumber(pi);
			break;
		case LUA_TSTRING:
			persiststring(pi);
			break;
		case LUA_TTABLE:
			persisttable(pi);
			break;
		case LUA_TFUNCTION:
			persistfunction(pi);
			break;
		case LUA_TTHREAD:
			persistthread(pi);
			break;
		case LUA_TPROTO:
			persistproto(pi);
			break;
		case LUA_TUPVAL:
			persistupval(pi);
			break;
		case LUA_TUSERDATA:
			persistuserdata(pi);
			break;
		default:
			lua_assert(0);
	}
#ifdef PLUTO_DEBUG
	pi->level--;
#endif
}
static int create(lua_State* pState)
{
    int mode = MODE_ECB;

    int top = lua_gettop(pState);
    size_t keyLen = 0;
    size_t IVLen = 0;
    int segment_size = 0;
    const char* key = NULL; 
    const char* IV = NULL;   
    AESObject* aes = NULL;

    key = luaL_checklstring(pState, 1, &keyLen);
    switch(keyLen) 
    {
        case 16:
        case 24:
        case 32:
            break;
        default:
            luaL_error(pState, "AES key must be either 16, 24, or 32 bytes long");
            return 0;
    }

    if (top > 1)
    {
        //check mode
        mode = luaL_checkint(pState, 2);
    }

    if (top > 2)
    {
        //check iv
        IV = luaL_checklstring(pState, 3, &IVLen);
    }

    if (top > 3)
    {
        //check segment size
        segment_size = luaL_checkint(pState, 4);
    }

    switch(mode)
    {
        case MODE_ECB:
        case MODE_CBC:
        case MODE_CFB:
        case MODE_OFB:
            break;
        default:
            luaL_error(pState, "Not Support AES Mode");
            return 0;
    }

    if (IVLen != BLOCK_SIZE && mode != MODE_ECB && mode != MODE_CTR)
    {
        luaL_error(pState, "IV must be %d bytes long", BLOCK_SIZE);
        return 0;
    }

    if (mode == MODE_CFB) 
    {
        if (segment_size == 0) 
            segment_size = 8;
        
        if (segment_size < 1 || segment_size > BLOCK_SIZE*8 
            || ((segment_size & 7) != 0)) 
        {
            luaL_error(pState,  "segment_size must be multiple of 8 (bits) between 1 and %d", BLOCK_SIZE*8);
            return 0;
        }
    }

    aes = (AESObject*)lua_newuserdata(pState, sizeof(AESObject));
    aes->mode = mode;
    aes->segment_size = segment_size;
    aes->count = BLOCK_SIZE;

    memset(aes->IV, 0, BLOCK_SIZE);
    memset(aes->oldCipher, 0, BLOCK_SIZE);
    memcpy(aes->IV, IV, IVLen);

    lua_pushlightuserdata(pState, &pycrypto_aes_key);
    lua_gettable(pState, LUA_REGISTRYINDEX);

    lua_setmetatable(pState, -2);

    if(block_init(&(aes->st), key, keyLen) != 0)
    {
        luaL_error(pState, "init aes object error %s %d", key, keyLen);
        return 0;
    }

    return 1;
}
Exemple #14
0
/* kpse:lookup("plain.tex", {}) */
static int do_lua_kpathsea_lookup(lua_State * L, kpathsea kpse, int idx)
{
    int i;
    string ret = NULL;
    string *ret_list = NULL;
    const_string name = NULL;
    string user_path = NULL;
    boolean show_all = false;
    boolean must_exist = false;
    kpse_file_format_type user_format = kpse_last_format;
    int dpi = 600;
    str_list_type subdir_paths = { 0, NULL };
    unsigned saved_debug = kpse->debug;
    int saved_mktexpk = kpse->format_info[kpse_pk_format].program_enabled_p;
    int saved_mktexmf = kpse->format_info[kpse_mf_format].program_enabled_p;
    int saved_mktextex = kpse->format_info[kpse_tex_format].program_enabled_p;
    int saved_mktextfm = kpse->format_info[kpse_tfm_format].program_enabled_p;
    name = luaL_checkstring(L, idx);
    /* todo: fetch parameter values */

    if (lua_type(L, idx + 1) == LUA_TTABLE) {
        lua_pushstring(L, "format");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TSTRING) {
            int op = luaL_checkoption(L, -1, NULL, filetypenames);
            user_format = filetypes[op];
        }
        lua_pop(L, 1);
        lua_pushstring(L, "dpi");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TNUMBER) {
            dpi = (int) lua_tointeger(L, -1);
        }
        lua_pop(L, 1);
        lua_pushstring(L, "debug");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TNUMBER) {
            int d = 0;
            d = (int) lua_tointeger(L, -1);
            kpse->debug |= d;
        }
        lua_pop(L, 1);
        lua_pushstring(L, "path");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TSTRING) {
            user_path = xstrdup(lua_tostring(L, -1));
        }
        lua_pop(L, 1);
        lua_pushstring(L, "all");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            show_all = lua_toboolean(L, -1);
        }
        lua_pop(L, 1);

        lua_pushstring(L, "mktexpk");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            kpathsea_maketex_option(kpse, "pk", lua_toboolean(L, -1));
        }
        lua_pop(L, 1);

        lua_pushstring(L, "mktextex");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            kpathsea_maketex_option(kpse, "tex", lua_toboolean(L, -1));
        }
        lua_pop(L, 1);

        lua_pushstring(L, "mktexmf");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            kpathsea_maketex_option(kpse, "mf", lua_toboolean(L, -1));
        }
        lua_pop(L, 1);

        lua_pushstring(L, "mktextfm");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            kpathsea_maketex_option(kpse, "tfm", lua_toboolean(L, -1));
        }
        lua_pop(L, 1);


        lua_pushstring(L, "mustexist");
        lua_gettable(L, idx + 1);
        if (lua_type(L, -1) == LUA_TBOOLEAN) {
            must_exist = lua_toboolean(L, -1);
        }
        lua_pop(L, 1);
        lua_pushstring(L, "subdir");
        lua_gettable(L, idx + 1);
        if (lua_istable(L, -1)) {
            lua_pushnil(L);
            while (lua_next(L, -2) != 0) {      /* numeric value */
                if (lua_type(L, -1) == LUA_TSTRING) {
                    char *s = xstrdup(lua_tostring(L, -1));
                    str_list_add(&subdir_paths, s);
                    xfree(s);
                }
                lua_pop(L, 1);
            }
        } else if (lua_type(L, -1) == LUA_TSTRING) {
            char *s = xstrdup(lua_tostring(L, -1));
            str_list_add(&subdir_paths, s);
            xfree(s);
        }
        lua_pop(L, 1);
        if (STR_LIST_LENGTH(subdir_paths) > 0) {
            show_all = 1;
        }
    }
    if (user_path) {
        /* Translate ; to : if that's our ENV_SEP.  See cnf.c.  */
        if (IS_ENV_SEP(':')) {
            string loc;
            for (loc = user_path; *loc; loc++) {
                if (*loc == ';')
                    *loc = ':';
            }
        }
        user_path = kpathsea_path_expand(kpse, user_path);
        if (show_all) {
            ret_list = kpathsea_all_path_search(kpse, user_path, name);
        } else {
            ret = kpathsea_path_search(kpse, user_path, name, must_exist);
        }
        free(user_path);
    } else {
        /* No user-specified search path, check user format or guess from NAME.  */
        kpse_file_format_type fmt;
        if (user_format != kpse_last_format)
            fmt = user_format;
        else
            fmt = find_format(kpse, name, true);

        switch (fmt) {
        case kpse_pk_format:
        case kpse_gf_format:
        case kpse_any_glyph_format:
            {
                kpse_glyph_file_type glyph_ret;
                string temp = remove_suffix (name);
                /* Try to extract the resolution from the name.  */
                unsigned local_dpi = find_dpi(name);
                if (!local_dpi)
                    local_dpi = (unsigned) dpi;
                ret =
                    kpathsea_find_glyph(kpse, temp, local_dpi,
                                        fmt, &glyph_ret);
                if (temp != name)
                    free (temp);
            }
            break;

        case kpse_last_format:
            /* If the suffix isn't recognized, assume it's a tex file. */
            fmt = kpse_tex_format;
            /* fall through */

        default:
            if (show_all) {
                ret_list =
                    kpathsea_find_file_generic(kpse, name, fmt, must_exist,
                                               true);
            } else {
                ret = kpathsea_find_file(kpse, name, fmt, must_exist);
            }
        }
    }

    /* Turn single return into a null-terminated list for uniform treatment.  */
    if (ret) {
        ret_list = XTALLOC(2, string);
        ret_list[0] = ret;
        ret_list[1] = NULL;
    }

    /* Filter by subdirectories, if specified.  */
    if (STR_LIST_LENGTH(subdir_paths) > 0) {
        string *new_list = subdir_match(subdir_paths, ret_list);
        free(ret_list);
        ret_list = new_list;
    }
    kpse->debug = saved_debug;
    kpse->format_info[kpse_pk_format].program_enabled_p = saved_mktexpk;
    kpse->format_info[kpse_mf_format].program_enabled_p = saved_mktexmf;
    kpse->format_info[kpse_tex_format].program_enabled_p = saved_mktextex;
    kpse->format_info[kpse_tfm_format].program_enabled_p = saved_mktextfm;

    /* Print output.  */
    i = 0;
    if (ret_list) {
        for (; ret_list[i]; i++) {
            lua_pushstring(L, ret_list[i]);
        }
        free(ret_list);
    }
    if (i == 0) {
        i++;
        lua_pushnil(L);
    }
    return i;
}
Exemple #15
0
int face_from_options(lua_State* L) {
  FT_Face face;
  FcChar8 * font_path, * fullname, * familyname;
  FcPattern* p;
  FcPattern* matched;
  FcResult result;
  int index = 0;

  const char *family = "Gentium";
  double pointSize = 12;
  int slant = FC_SLANT_ROMAN;
  int weight = 100;
  const char *script = "latin";
  const char *language = "eng";
  int direction = HB_DIRECTION_LTR;

  if (!lua_istable(L, 1)) return 0;

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

  lua_pushstring(L, "filename");
  lua_gettable(L, -2);
  if (lua_isstring(L, -1)) {
    font_path = lua_tostring(L, -1);
    lua_pop(L,1);
    lua_newtable(L);
    lua_pushstring(L, "filename");
    lua_pushstring(L, (char*)font_path);
    lua_settable(L, -3);
    goto done_match;
  }
  lua_pop(L,1);

  lua_pushstring(L, "font");
  lua_gettable(L, -2);
  if (lua_isstring(L, -1)) { family = lua_tostring(L, -1); }
  lua_pop(L,1);

  lua_pushstring(L, "weight");
  lua_gettable(L, -2);
  if (lua_isnumber(L, -1)) {
    int newWeight = lua_tointeger(L, -1);
    if      (newWeight <= 100) newWeight = FC_WEIGHT_THIN;
    else if (newWeight <= 200) newWeight = FC_WEIGHT_ULTRALIGHT;
    else if (newWeight <= 300) newWeight = FC_WEIGHT_LIGHT;
    else if (newWeight <= 400) newWeight = FC_WEIGHT_NORMAL;
    else if (newWeight <= 500) newWeight = FC_WEIGHT_MEDIUM;
    else if (newWeight <= 600) newWeight = FC_WEIGHT_DEMIBOLD;
    else if (newWeight <= 700) newWeight = FC_WEIGHT_BOLD;
    else if (newWeight <= 800) newWeight = FC_WEIGHT_ULTRABOLD;
    else                       newWeight = FC_WEIGHT_HEAVY;
    weight = newWeight;
  }
  lua_pop(L,1);

  lua_pushstring(L, "language");
  lua_gettable(L, -2);
  if (lua_isstring(L, -1)) { language = lua_tostring(L, -1); }
  lua_pop(L,1);

  lua_pushstring(L, "style");
  lua_gettable(L, -2);
  if (lua_isstring(L, -1)) {
    const char* newStyleAsText = lua_tostring(L, -1);
    if (!strcmp(newStyleAsText, "italic"))
      slant = FC_SLANT_ITALIC;
  }
  lua_pop(L,1);

  p = FcPatternCreate();

  FcPatternAddString (p, FC_FAMILY, (FcChar8*)(family));
  FcPatternAddDouble (p, FC_SIZE, pointSize);
  FcPatternAddInteger(p, FC_SLANT, slant);
  FcPatternAddInteger(p, FC_WEIGHT, weight);

  // /* Add fallback fonts here. Some of the standard 14 should be fine. */
  FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Times-Roman");
  FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Times");
  FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Helvetica");
  matched = FcFontMatch (0, p, &result);
  
  if (FcPatternGetString (matched, FC_FILE, 0, &font_path) != FcResultMatch)
    return 0;
  
  FcPatternGetInteger(matched, FC_INDEX, 0, &index);
  font_path = (FcChar8 *)strdup((char*)font_path); /* XXX signedness problems? */
  if (!font_path) {
    printf("Finding font path failed\n");
    return 0;
  }
  /* Push back slant and weight, we need to pass them to libpdftex */
  FcPatternGetInteger(matched, FC_SLANT, 0, &slant);
  FcPatternGetInteger(matched, FC_WEIGHT, 0, &weight);

  /* Find out which family we did actually pick up */
  if (FcPatternGetString (matched, FC_FAMILY, 0, &familyname) != FcResultMatch)
    return 0;

  lua_newtable(L);
  lua_pushstring(L, "filename");
  lua_pushstring(L, (char*)font_path);
  lua_settable(L, -3);

  lua_pushstring(L, "family");
  lua_pushstring(L, (char*)(familyname));
  lua_settable(L, -3);

  if (FcPatternGetString (matched, FC_FULLNAME, 0, &fullname) == FcResultMatch) {
    lua_pushstring(L, "fullname");
    lua_pushstring(L, (char*)(fullname));
    lua_settable(L, -3);
  }

  FcPatternDestroy (matched);
  FcPatternDestroy (p);

  done_match:
  face = (FT_Face)malloc(sizeof(FT_Face));
  if (FT_New_Face(ft_library, (char*)font_path, index, &face))
    return 0;

  if (FT_Set_Char_Size(face,pointSize * 64.0, 0, 0, 0))
    return 0;

  lua_pushstring(L, "index");
  lua_pushinteger(L, index);
  lua_settable(L, -3);

  lua_pushstring(L, "pointsize");
  lua_pushnumber(L, pointSize);
  lua_settable(L, -3);

  lua_pushstring(L, "face");
  lua_pushlightuserdata(L, face);
  lua_settable(L, -3);

  return 1;
}
QString luaTrajectory::pop(lua_State *luaL, QStringList& attribs)
{
#ifdef DEBUG_OBSERVER
    printf("\ngetState - Trajectory\n\n");
    luaStackToQString(12);

    qDebug() << attribs;
#endif

    QString msg;

    // id
    msg.append("trajectory");
    msg.append(QString::number(ref));
    msg.append(PROTOCOL_SEPARATOR);

    // subjectType
    msg.append(QString::number(subjectType));
    msg.append(PROTOCOL_SEPARATOR);

    int pos = lua_gettop(luaL);

    //------------
    int attrCounter = 0;
    int elementCounter = 0;
    // bool contains = false;
    double num = 0;
    QString text, key, attrs, elements;

    lua_pushnil(luaL);
    while(lua_next(luaL, pos ) != 0)
    {
        if (lua_type(luaL, -2) == LUA_TSTRING)
        {
            key = QString(luaL_checkstring(luaL, -2));
        }
        else
        {
            if (lua_type(luaL, -2) == LUA_TNUMBER)
            {
                char aux[100];
                double number = luaL_checknumber(luaL, -2);
                sprintf(aux, "%g", number);
                key = QString(aux);
            }
        }

        if ((attribs.contains(key)) || (key == "cells"))
        {
            attrCounter++;
            attrs.append(key);
            attrs.append(PROTOCOL_SEPARATOR);

            switch( lua_type(luaL, -1) )
            {
            case LUA_TBOOLEAN:
                attrs.append(QString::number(TObsBool));
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString::number( lua_toboolean(luaL, -1)));
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TNUMBER:
                num = luaL_checknumber(luaL, -1);
                attrs.append(QString::number(TObsNumber));
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString::number(num));
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TSTRING:
                text = QString(luaL_checkstring(luaL, -1));
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append( (text.isEmpty() || text.isNull() ? VALUE_NOT_INFORMED : text) );
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TTABLE:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append("Lua-Address(TB): " + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);

                // Recupera a tabela de cells e delega a cada
                // celula sua serialização
                // if(key == "cells")
                //{
                int top = lua_gettop(luaL);

                lua_pushnil(luaL);
                while(lua_next(luaL, top) != 0)
                {
                    int cellTop = lua_gettop(luaL);
                    lua_pushstring(luaL, "cObj_");
                    lua_gettable(luaL, cellTop);

                    luaCell*  cell;
                    cell = (luaCell*)Luna<luaCell>::check(L, -1);
                    lua_pop(luaL, 1);

                    // luaCell->popCell(...) requer uma celula no topo da pilha
                    QString cellMsg = cell->pop(L, QStringList() << "x" << "y");
                    elements.append(cellMsg);
                    elementCounter++;

                    lua_pop(luaL, 1);
                }
                break;
                // }
                // break;
            }

            case LUA_TUSERDATA	:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append("Lua-Address(UD): " + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }

            case LUA_TFUNCTION:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString("Lua-Address(FT): ") + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }

            default:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString("Lua-Address(O): ") + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }
            }
        }
        lua_pop(luaL, 1);
    }

    // #attrs
    msg.append(QString::number(attrCounter));
    msg.append(PROTOCOL_SEPARATOR );

    // #elements
    msg.append(QString::number(elementCounter));
    msg.append(PROTOCOL_SEPARATOR );
    msg.append(attrs);

    msg.append(PROTOCOL_SEPARATOR);
    msg.append(elements);
    msg.append(PROTOCOL_SEPARATOR);

#ifdef DEBUG_OBSERVER
    // save(msg);
    // qDebug() << msg.split(PROTOCOL_SEPARATOR); //, QString::SkipEmptyParts);
#endif

    return msg;
}
	inline void VLuaWrapper::PushTable (const char* szTableName, bool bGlobalTable)
	{
		lua_pushstring (mp_State, szTableName);
		lua_gettable (mp_State, ((bGlobalTable) || (m_States.m_iOpenTables == 0)) ? LUA_GLOBALSINDEX : -2);
		m_States.m_iParametersPushed++;
	}
Exemple #18
0
static int getScript(lua_State* L) {
	BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
	lua_pushinteger(L, barrier->GetScriptReference());
	lua_gettable(L, LUA_REGISTRYINDEX);
	return 1;
}
void send()
{
    lua_getglobal(L, "RAW");

    /* menu */
    lua_pushstring(L, "menu");
    lua_pushinteger(L, 999);
    lua_rawset(L, -3);

    /* dt*/
    lua_pushstring(L, "dt");
    lua_pushnumber(L, 0.016666666);
    lua_rawset(L, -3);

    /* model gyro */
    lua_pushstring(L, "gyr");
    lua_gettable(L, -2);
    {
        lua_pushstring(L, "x");
        lua_pushnumber(L, 0.00001);
        lua_rawset(L, -3);

        lua_pushstring(L, "y");
        lua_pushnumber(L, 0.00002);
        lua_rawset(L, -3);

        lua_pushstring(L, "z");
        lua_pushnumber(L, 0.00003);
        lua_rawset(L, -3);
    }
    lua_pop(L, 1);

    /* model acc */
    lua_pushstring(L, "acc");
    lua_gettable(L, -2);
    {
        lua_pushstring(L, "x");
        lua_pushnumber(L, 0.0);
        lua_rawset(L, -3);

        lua_pushstring(L, "y");
        lua_pushnumber(L, 0.0);
        lua_rawset(L, -3);

        lua_pushstring(L, "z");
        lua_pushnumber(L, -9.81);
        lua_rawset(L, -3);
    }
    lua_pop(L, 1);

    /* lat/lon/alt */
    lua_pushstring(L, "gps");
    lua_gettable(L, -2);
    {
        lua_pushstring(L, "lat");
        lua_pushnumber(L, 58.5);
        lua_rawset(L, -3);

        lua_pushstring(L, "lon");
        lua_pushnumber(L, 31.25);
        lua_rawset(L, -3);

        lua_pushstring(L, "alt");
        lua_pushnumber(L, 22);
        lua_rawset(L, -3);
    }
    lua_pop(L, 1);

    lua_pop(L, 1);


    lua_getglobal(L, "TX");
    for (int i = 0; i < 39; i++) {
        lua_pushinteger(L, i+1);
        lua_pushnumber(L, (float)(i+1) * 0.01);
        lua_rawset(L, -3);
    }
    lua_pop(L, 1);

    lua_pushcfunction(L, errorHandler);
    lua_getglobal(L, "main");
    int result = lua_pcall(L, 0, 0, -2);
    if (result) {
        printf("send() failed\n");
    }
    lua_pop(L, 1);
}
bool cMeshBuilder::LoadTableValues_parameters_values(lua_State& io_luaState, const char * field_value)
{
	if (strcmp(field_value, "vertex") == 0)
	{
		//lua_pushnil(&io_luaState);
		//std::cout << "in Para-2metres: \n";
		//std::cout << "Length " << luaL_len(&io_luaState,-2) << "\n";
		//while (lua_next(&io_luaState, -2))
		int lengthVector = luaL_len(&io_luaState, -1);
		//std::cout << "Length " << lengthVector << "\n";
		const int numberOfParameters = 17;
		float * vertexinfo = new float[lengthVector * numberOfParameters];
		unsigned int vertexInfo_index = 0;
		for (int i = 0; i < lengthVector; i++)
		{
			lua_pushinteger(&io_luaState, i+1);
			lua_gettable(&io_luaState, -2);
			//if (lua_istable(&io_luaState, -1))
			const int lengthInfo = static_cast<const int>(luaL_len(&io_luaState, -1));
			float key3[numberOfParameters] = {};
			for (int j = 0; j < lengthInfo; j++)
			{
				lua_pushinteger(&io_luaState, j+1);
				lua_gettable(&io_luaState, -2);
				
				*(vertexinfo + vertexInfo_index) = static_cast< float >(lua_tonumber(&io_luaState, -1));
				key3[j] = static_cast< float >(lua_tonumber(&io_luaState, -1));
				vertexInfo_index++;
				lua_pop(&io_luaState, 1);
			}
			lua_pop(&io_luaState, 1);
		}
		_rout->write((char*)vertexinfo, sizeof(float)* numberOfParameters * lengthVector);
		delete[] vertexinfo;
	}
	else if (strcmp(field_value, "indices") == 0)
	{
		int lengthFaces = luaL_len(&io_luaState, -1);
		int * indicesinfo = new int[lengthFaces * 6];
		unsigned int indicesInfo_index = 0;
		for (int i = 0; i < lengthFaces; i++)
		{
			lua_pushinteger(&io_luaState, i + 1);
			lua_gettable(&io_luaState, -2);
			//if (lua_istable(&io_luaState, -1))
			const int lengthInfo = static_cast<const int>(luaL_len(&io_luaState, -1));
			for (int j = 0; j < lengthInfo; j++)
			{
				lua_pushinteger(&io_luaState, j + 1);
				lua_gettable(&io_luaState, -2);

				*(indicesinfo + indicesInfo_index) = static_cast< int >(lua_tonumber(&io_luaState, -1));
				indicesInfo_index++;
				lua_pop(&io_luaState, 1);
			}
			lua_pop(&io_luaState, 1);
		}
		_rout->write((char*)indicesinfo, sizeof(int)* 6 * lengthFaces);
		delete[] indicesinfo;
	}
	return true;
}
Exemple #21
0
Messenger* lua_getMessenger(lua_State *L) {
    lua_pushstring(L, LUA_REGISTRY_MESSENGER);
    lua_gettable(L, LUA_REGISTRYINDEX);
    Messenger* messenger = (Messenger *) lua_touserdata(L, -1);
    return messenger;
}
Exemple #22
0
int Xml_eval(lua_State *L) {
	char* str = 0;
	size_t str_size=0;
	if(lua_isuserdata(L,1)) str = (char*)lua_touserdata(L,1);
	else {
		const char * sTmp = luaL_checklstring(L,1,&str_size);
		str = (char*)malloc(str_size+1);
		memcpy(str, sTmp, str_size);
		str[str_size]=0;
	}
	Tokenizer* tok = Tokenizer_new(str, str_size ? str_size : strlen(str));
	lua_settop(L,0);
	const char* token=0;
	int firstStatement = 1;
	while((token=Tokenizer_next(tok))!=0) if(token[0]==OPN) { // new tag found
		if(lua_gettop(L)) {
			int newIndex=lua_objlen(L,-1)+1;
			lua_pushnumber(L,newIndex);
			lua_newtable(L);
			lua_settable(L, -3);
			lua_pushnumber(L,newIndex);
			lua_gettable(L,-2);
		}
		else {
			if (firstStatement) {
				lua_newtable(L); 
				firstStatement = 0;
			}
			else return lua_gettop(L);
		}
		// set metatable:    
		lua_newtable(L);
		lua_pushliteral(L, "__index");
		lua_getglobal(L, "xml");
		lua_settable(L, -3);
			
		lua_pushliteral(L, "__tostring"); // set __tostring metamethod
		lua_getglobal(L, "xml");
		lua_pushliteral(L,"str");
		lua_gettable(L, -2);
		lua_remove(L, -2);
		lua_settable(L, -3);			
		lua_setmetatable(L, -2);
		
		// parse tag and content:
		lua_pushnumber(L,0); // use index 0 for storing the tag
		lua_pushstring(L, Tokenizer_next(tok));
		lua_settable(L, -3);
		
		while(((token = Tokenizer_next(tok))!=0)&&(token[0]!=CLS)&&(token[0]!=ESC)) { // parse tag header
			size_t sepPos=find(token, "=", 0);
			if(token[sepPos]) { // regular attribute
				const char* aVal =token+sepPos+2;
				lua_pushlstring(L, token, sepPos);
				Xml_pushDecode(L, aVal, strlen(aVal)-1);
				lua_settable(L, -3);
			}
		}            
		if(!token||(token[0]==ESC)) {
			if(lua_gettop(L)>1) lua_settop(L,-2); // this tag has no content, only attributes
			else break;
		}
	}
	else if(token[0]==ESC) { // previous tag is over
		if(lua_gettop(L)>1) lua_settop(L,-2); // pop current table
		else break;
	}
	else { // read elements
		lua_pushnumber(L,lua_objlen(L,-1)+1);
		Xml_pushDecode(L, token, 0);
		lua_settable(L, -3);
	}
	Tokenizer_delete(tok);
	free(str);
	return lua_gettop(L);
}
bool luaval_to_ccluavaluevector(lua_State* L, int lo, LuaValueArray* ret, const char* funcName)
{
    if (nullptr == L || nullptr == ret)
        return false;

    tolua_Error tolua_err;
    bool ok = true;
    if (!tolua_istable(L, lo, 0, &tolua_err))
    {
#if COCOS2D_DEBUG >=1
        // luaval_to_native_err(L,"#ferror:",&tolua_err);
#endif
        ok = false;
    }

    if (ok)
    {
        size_t len = lua_objlen(L, lo);
        for (size_t i = 0; i < len; i++)
        {
            lua_pushnumber(L,i + 1);
            lua_gettable(L,lo);
            if (lua_isnil(L,-1))
            {
                lua_pop(L, 1);
                continue;
            }

            if(lua_istable(L, -1))
            {
                lua_pushnumber(L,1);
                lua_gettable(L,-2);
                if (lua_isnil(L, -1) )
                {
                    lua_pop(L,1);
                    LuaValueDict dictVal;
                    if (luaval_to_ccluavaluemap(L, lua_gettop(L), &dictVal))
                    {
                        ret->push_back(LuaValue::dictValue(dictVal));
                    }
                }
                else
                {
                    lua_pop(L,1);
                    LuaValueArray arrVal;
                    if(luaval_to_ccluavaluevector(L, lua_gettop(L), &arrVal))
                    {
                        ret->push_back(LuaValue::arrayValue(arrVal));
                    }
                }
            }
            else if(lua_type(L, -1) == LUA_TSTRING)
            {
                std::string stringValue = "";
                if(luaval_to_std_string(L, -1, &stringValue) )
                {
                    ret->push_back(LuaValue::stringValue(stringValue));
                }
            }
            else if(lua_type(L, -1) == LUA_TBOOLEAN)
            {
                bool boolVal = false;
                if (luaval_to_boolean(L, -1, &boolVal))
                {
                    ret->push_back(LuaValue::booleanValue(boolVal));
                }
            }
            else if(lua_type(L, -1) == LUA_TNUMBER)
            {
                ret->push_back(LuaValue::floatValue(tolua_tonumber(L, -1, 0)));
            }
            else
            {
                //                CCASSERT(false, "not supported type");
            }
            lua_pop(L, 1);
        }
    }

    return ok;
}
Exemple #24
0
int luaRedisGenericCommand(lua_State *lua, int raise_error) {
    int j, argc = lua_gettop(lua);
    struct redisCommand *cmd;
    robj **argv;
    redisClient *c = server.lua_client;
    sds reply;

    // 参数必须大于零
    /* Require at least one argument */
    if (argc == 0) {
        luaPushError(lua,
            "Please specify at least one argument for redis.call()");
        return 1;
    }

    // 处理参数
    /* Build the arguments vector */
    argv = zmalloc(sizeof(robj*)*argc);
    for (j = 0; j < argc; j++) {
        if (!lua_isstring(lua,j+1)) break;
        argv[j] = createStringObject((char*)lua_tostring(lua,j+1),
                                     lua_strlen(lua,j+1));
    }

    /* Check if one of the arguments passed by the Lua script
     * is not a string or an integer (lua_isstring() return true for
     * integers as well). */
    if (j != argc) {
        j--;
        while (j >= 0) {
            decrRefCount(argv[j]);
            j--;
        }
        zfree(argv);
        luaPushError(lua,
            "Lua redis() command arguments must be strings or integers");
        return 1;
    }

    // 将参数设置为虚拟客户端的参数
    /* Setup our fake client for command execution */
    c->argv = argv;
    c->argc = argc;

    // 查找命令
    /* Command lookup */
    cmd = lookupCommand(argv[0]->ptr);
    if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||
                   (argc < -cmd->arity)))
    {
        if (cmd)
            luaPushError(lua,
                "Wrong number of args calling Redis command From Lua script");
        else
            luaPushError(lua,"Unknown Redis command called from Lua script");
        goto cleanup;
    }

    /* There are commands that are not allowed inside scripts. */
    if (cmd->flags & REDIS_CMD_NOSCRIPT) {
        luaPushError(lua, "This Redis command is not allowed from scripts");
        goto cleanup;
    }

    /* Write commands are forbidden against read-only slaves, or if a
     * command marked as non-deterministic was already called in the context
     * of this script. */
    // 涉及写操作的命令
    if (cmd->flags & REDIS_CMD_WRITE) {
        // 如果曾经 lua 脚本中执行未决命令,譬如 RANDOMKEY,那么写操作是不
        // 允许的
        if (server.lua_random_dirty) {
            luaPushError(lua,
                "Write commands not allowed after non deterministic commands");
            goto cleanup;

        // 此服务器为设定了只读的从机,且未处于加载数据阶段,那么写操作是不
        // 允许的
        } else if (server.masterhost && server.repl_slave_ro &&
                   !server.loading &&
                   !(server.lua_caller->flags & REDIS_MASTER))
        {
            luaPushError(lua, shared.roslaveerr->ptr);
            goto cleanup;

        // 如果设定了当 BGSAVE 失败时不能执行写操作,而且 BGSAVE 失败了,
        // 那么写操作是不允许的
        // server.stop_writes_on_bgsave_err 选项是说默认当 BGSAVE 持久化
        // 失败的时候,禁止接受写操作。当客户端发现写操作失败的时候,可以及时
        // 发现 redis 服务器持久化失败了,因此,这是给客户端发现持久化失败的
        // 机会
        } else if (server.stop_writes_on_bgsave_err &&
                   server.saveparamslen > 0 &&
                   server.lastbgsave_status == REDIS_ERR)
        {
            luaPushError(lua, shared.bgsaveerr->ptr);
            goto cleanup;
        }
    }

    // 内存超出预设值,执行淘汰策略
    /* If we reached the memory limit configured via maxmemory, commands that
     * could enlarge the memory usage are not allowed, but only if this is the
     * first write in the context of this script, otherwise we can't stop
     * in the middle. */
    if (server.maxmemory && server.lua_write_dirty == 0 &&
        (cmd->flags & REDIS_CMD_DENYOOM))
    {
        if (freeMemoryIfNeeded() == REDIS_ERR) {
            luaPushError(lua, shared.oomerr->ptr);
            goto cleanup;
        }
    }

    // 标记涉及随机和写操作
    if (cmd->flags & REDIS_CMD_RANDOM) server.lua_random_dirty = 1;
    if (cmd->flags & REDIS_CMD_WRITE) server.lua_write_dirty = 1;

    // 执行命令
    // c 实际上是一个虚拟的客户端,虚拟客户端即是为了复用普通命令处理函数
    // 以 get 命令的处理函数为例:
    // void getCommand(redisClient *c);
    /* Run the command */
    c->cmd = cmd;
    call(c,REDIS_CALL_SLOWLOG | REDIS_CALL_STATS);

    /* Convert the result of the Redis command into a suitable Lua type.
     * The first thing we need is to create a single string from the client
     * output buffers. */
    // 拷贝 redisClient 的处理结果
    reply = sdsempty();
    if (c->bufpos) {
        reply = sdscatlen(reply,c->buf,c->bufpos);
        c->bufpos = 0;
    }
    // 删除 redisClient 内的处理结果
    while(listLength(c->reply)) {
        robj *o = listNodeValue(listFirst(c->reply));

        reply = sdscatlen(reply,o->ptr,sdslen(o->ptr));
        listDelNode(c->reply,listFirst(c->reply));
    }
    if (raise_error && reply[0] != '-') raise_error = 0;
    redisProtocolToLuaType(lua,reply);
    /* Sort the output array if needed, assuming it is a non-null multi bulk
     * reply as expected. */
    if ((cmd->flags & REDIS_CMD_SORT_FOR_SCRIPT) &&
        (reply[0] == '*' && reply[1] != '-')) {
            luaSortArray(lua);
    }
    sdsfree(reply);
    c->reply_bytes = 0;

cleanup:
    /* Clean up. Command code may have changed argv/argc so we use the
     * argv/argc of the client instead of the local variables. */
    for (j = 0; j < c->argc; j++)
        decrRefCount(c->argv[j]);
    zfree(c->argv);

    if (raise_error) {
        /* If we are here we should have an error in the stack, in the
         * form of a table with an "err" field. Extract the string to
         * return the plain error. */
        lua_pushstring(lua,"err");
        lua_gettable(lua,-2);
        return lua_error(lua);
    }
    return 1;
}
Exemple #25
0
void LuaConsole::UpdateCompletion(const std::string & statement) {
	// First, split the statement into chunks.
	m_completionList.clear();
	std::stack<std::string> chunks;
	bool method = false;
	bool expect_symbolname = false;
	std::string::const_iterator current_end = statement.end();
	std::string::const_iterator current_begin = statement.begin(); // To keep record when breaking off the loop.
	for (std::string::const_reverse_iterator r_str_it = statement.rbegin();
			r_str_it != statement.rend(); ++r_str_it) {
		if(Text::is_alphanumunderscore(*r_str_it)) {
			expect_symbolname = false;
			continue;
		} else if (expect_symbolname) // Wrong syntax.
			return;
		if(*r_str_it != '.' && (!chunks.empty() || *r_str_it != ':')) { // We are out of the expression.
			current_begin = r_str_it.base(); // Flag the symbol marking the beginning of the expression.
			break;
		}

		expect_symbolname = true; // We hit a separator, there should be a symbol name before it.
		chunks.push(std::string(r_str_it.base(), current_end));
		if (*r_str_it == ':') // If it is a colon, we know chunks is empty so it is incomplete.
			method = true;		// it must mean that we want to call a method.
		current_end = (r_str_it+1).base(); // +1 in order to point on the CURRENT character.
	}
	if (expect_symbolname) // Again, a symbol was expected when we broke out of the loop.
		return;

	if (current_begin != current_end)
		chunks.push(std::string(current_begin, current_end));

	if (chunks.empty()) {
		return;
	}

	lua_State * l = Lua::manager->GetLuaState();
	int stackheight = lua_gettop(l);
	lua_rawgeti(l, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
	// Loading the tables in which to do the name lookup
	while (chunks.size() > 1) {
		if (!lua_istable(l, -1) && !lua_isuserdata(l, -1))
			break; // Goes directly to the cleanup code anyway.
		lua_pushstring(l, chunks.top().c_str());
		lua_gettable(l, -2);
		chunks.pop();
	}
	if (lua_istable(l, -1))
		fetch_keys_from_table(l, -1, chunks.top(), m_completionList, method);
	if (lua_getmetatable(l, -1)) {
		try {
			fetch_keys_from_metatable(l, -1, chunks.top(), m_completionList, method);
		} catch (RecursionLimit &) {
			AddOutput("Warning: The recursion limit has been hit during the completion run.");
			AddOutput("         There is most likely a recursion within the metatable structure.");
		}
	}
	if(!m_completionList.empty()) {
		std::sort(m_completionList.begin(), m_completionList.end());
		m_completionList.erase(std::unique(m_completionList.begin(), m_completionList.end()), m_completionList.end());
		// Add blank completion at the end of the list and point to it.
		m_currentCompletion = m_completionList.size();
		m_completionList.push_back("");

		m_precompletionStatement = statement;
	}
	lua_pop(l, lua_gettop(l)-stackheight); // Clean the whole stack.
}
Exemple #26
0
void luaReplyToRedisReply(redisClient *c, lua_State *lua) {
    int t = lua_type(lua,-1);

    switch(t) {
    case LUA_TSTRING:
        addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1));
        break;
    case LUA_TBOOLEAN:
        addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk);
        break;
    case LUA_TNUMBER:
        addReplyLongLong(c,(long long)lua_tonumber(lua,-1));
        break;
    case LUA_TTABLE:
        /* We need to check if it is an array, an error, or a status reply.
         * Error are returned as a single element table with 'err' field.
         * Status replies are returned as single element table with 'ok' field */
        lua_pushstring(lua,"err");
        lua_gettable(lua,-2);
        t = lua_type(lua,-1);
        if (t == LUA_TSTRING) {
            sds err = sdsnew(lua_tostring(lua,-1));
            sdsmapchars(err,"\r\n","  ",2);
            addReplySds(c,sdscatprintf(sdsempty(),"-%s\r\n",err));
            sdsfree(err);
            lua_pop(lua,2);
            return;
        }

        lua_pop(lua,1);
        lua_pushstring(lua,"ok");
        lua_gettable(lua,-2);
        t = lua_type(lua,-1);
        if (t == LUA_TSTRING) {
            sds ok = sdsnew(lua_tostring(lua,-1));
            sdsmapchars(ok,"\r\n","  ",2);
            addReplySds(c,sdscatprintf(sdsempty(),"+%s\r\n",ok));
            sdsfree(ok);
            lua_pop(lua,1);
        } else {
            void *replylen = addDeferredMultiBulkLength(c);
            int j = 1, mbulklen = 0;

            lua_pop(lua,1); /* Discard the 'ok' field value we popped */
            while(1) {
                lua_pushnumber(lua,j++);
                lua_gettable(lua,-2);
                t = lua_type(lua,-1);
                if (t == LUA_TNIL) {
                    lua_pop(lua,1);
                    break;
                }
                luaReplyToRedisReply(c, lua);
                mbulklen++;
            }
            setDeferredMultiBulkLength(c,replylen,mbulklen);
        }
        break;
    default:
        addReply(c,shared.nullbulk);
    }
    lua_pop(lua,1);
}
Exemple #27
0
/*---------------------------------------------------------------------------*/ 
void lua_tinker::push_meta(lua_State *L, const char* name)
{
	lua_pushstring(L, name);
	lua_gettable(L, LUA_GLOBALSINDEX);
}
Exemple #28
0
int lua_header(lua_State *L)
{
    epdata_t *epd = get_epd(L);

    if(!epd) {
        lua_pushnil(L);
        lua_pushstring(L, "miss epd!");
        return 2;
    }

    if(epd->websocket) {
        return 0;
    }

    if(lua_gettop(L) < 1) {
        return 0;
    }

    if(epd->header_sended != 0) {
        lua_pushnil(L);
        lua_pushstring(L, "respone header has been sended");
        return 2;
    }

    int t = lua_type(L, 1);
    size_t dlen = 0;
    const char *data = NULL;
    int ret = 0;

    if(t == LUA_TSTRING) {
        data = lua_tolstring(L, 1, &dlen);

        if(stristr(data, "content-length", dlen) != data) {
            ret = network_send_header(epd, data);
        }

    } else if(t == LUA_TTABLE) {
        int len = lua_objlen(L, 1), i = 0;

        for(i = 0; i < len; i++) {
            lua_pushinteger(L, i + 1);
            lua_gettable(L, -2);

            if(lua_isstring(L, -1)) {
                data = lua_tolstring(L, -1, &dlen);

                if(stristr(data, "content-length", dlen) != data) {
                    ret = network_send_header(epd, lua_tostring(L, -1));
                }
            }

            lua_pop(L, 1);
        }
    }

    if(ret == -1) {
        lua_pushnil(L);
        lua_pushstring(L, "respone header too big");
        return 2;

    } else if(ret == 0) {
        lua_pushnil(L);

    } else {
        lua_pushboolean(L, 1);
    }

    return 1;
}
Exemple #29
0
/*************************************************************************
    Pushes a named function on the stack
*************************************************************************/
void LuaFunctor::pushNamedFunction(lua_State* L, const String& handler_name)
{
    int top = lua_gettop(L);

    // do we have any dots in the handler name? if so we grab the function as a table field
    String::size_type i = handler_name.find_first_of((utf32)'.');
    if (i!=String::npos)
    {
        // split the rest of the string up in parts seperated by '.'
        // TODO: count the dots and size the vector accordingly from the beginning.
        std::vector<String> parts;
        String::size_type start = 0;
        do
        {
            parts.push_back(handler_name.substr(start,i-start));
            start = i+1;
            i = handler_name.find_first_of((utf32)'.',start);
        } while(i!=String::npos);

        // add last part
        parts.push_back(handler_name.substr(start));

        // first part is the global
        lua_getglobal(L, parts[0].c_str());
        if (!lua_istable(L,-1))
        {
            lua_settop(L,top);
            CEGUI_THROW(ScriptException("Unable to get the Lua event handler: '"+handler_name+"' as first part is not a table"));
        }

        // if there is more than two parts, we have more tables to go through
        std::vector<String>::size_type visz = parts.size();
        if (visz-- > 2) // avoid subtracting one later on
        {
            // go through all the remaining parts to (hopefully) have a valid Lua function in the end
            std::vector<String>::size_type vi = 1;
            while (vi<visz)
            {
                // push key, and get the next table
                lua_pushstring(L,parts[vi].c_str());
                lua_gettable(L,-2);
                if (!lua_istable(L,-1))
                {
                    lua_settop(L,top);
                    CEGUI_THROW(ScriptException("Unable to get the Lua event handler: '"+handler_name+"' as part #"+PropertyHelper::uintToString(uint(vi+1))+" ("+parts[vi]+") is not a table"));
                }
                // get rid of the last table and move on
                lua_remove(L,-2);
                vi++;
            }
        }

        // now we are ready to get the function to call ... phew :)
        lua_pushstring(L,parts[visz].c_str());
        lua_gettable(L,-2);
        lua_remove(L,-2); // get rid of the table
    }
    // just a regular global function
    else
    {
        lua_getglobal(L, handler_name.c_str());
    }

    // is it a function
    if (!lua_isfunction(L,-1))
    {
        lua_settop(L,top);
        CEGUI_THROW(ScriptException("The Lua event handler: '"+handler_name+"' does not represent a Lua function"));
    }
}
Exemple #30
0
void     LuaAgent::GetTable(int idx)
{
    lua_gettable(luaState,idx);
}