Example #1
0
File: lpng.c Project: lvshaco/lpng
static int
lload(lua_State *L) {
    int top = lua_gettop(L);
    FILE *fp; 
    struct png_source source;
    if (top == 1) {
        const char *filename = luaL_checkstring(L,1);
        fp = fopen(filename, "rb");
        if (fp == NULL) {
            return luaL_error(L, strerror(errno));
        }
        unsigned char header[PNGSIGSIZE];
        if (fread(header, 1, PNGSIGSIZE, fp) != PNGSIGSIZE) {
            return luaL_error(L, "png invalid");
        }
        if (png_sig_cmp(header, 0, PNGSIGSIZE)) {
            return luaL_error(L, "png sig invalid");
        }
        fseek(fp, 0, SEEK_SET);
    } else if (top == 2) {
        luaL_checktype(L,1,LUA_TLIGHTUSERDATA);
        void *data = lua_touserdata(L,1);
        size_t size = luaL_checkinteger(L,2);
        if (size < PNGSIGSIZE) {
            return luaL_error(L, "png invalid");
        }
        if (png_sig_cmp(data, 0, PNGSIGSIZE)) {
            return luaL_error(L, "png sig invalid");
        }
        source.data = data;
        source.size = size;
        source.offset = 0;
    } else {
        return luaL_error(L, "invalid argument number");
    }
    
    png_structp png_ptr;
    png_infop info_ptr;
    png_uint_32 width, height;
    int bit_depth, color_type, interlace_type;
    int step;//, type;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL) {
        return 0;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        png_destroy_read_struct(&png_ptr, NULL, NULL);
        return 0;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        return 0;
    }

    if (top == 1)
        png_init_io(png_ptr, fp);
    else
        png_set_read_fn(png_ptr, (void *)&source, png_read_cb);

    //png_set_sig_bytes(png_ptr, PNGSIGSIZE);

    png_read_info(png_ptr, info_ptr);

    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
            &interlace_type, NULL, NULL);

    if (color_type == PNG_COLOR_TYPE_PALETTE)
        png_set_palette_to_rgb(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
        bit_depth = 8;
        png_set_expand_gray_1_2_4_to_8(png_ptr);
    }

    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) != 0)
        png_set_tRNS_to_alpha(png_ptr);

    if (bit_depth == 16)
        png_set_strip_16(png_ptr);

    if (bit_depth < 8)
        png_set_packing(png_ptr);

    png_read_update_info(png_ptr, info_ptr);
    bit_depth = png_get_bit_depth(png_ptr, info_ptr);
    color_type = png_get_color_type(png_ptr, info_ptr);
    switch (color_type) {
    case PNG_COLOR_TYPE_GRAY:
        // type = TEXTURE_DEPTH;
        step = 1;
        break;
    case PNG_COLOR_TYPE_RGB:
        //type = TEXTURE_RGB;
        step = 3;
        break;
    case PNG_COLOR_TYPE_RGB_ALPHA:
        //type = TEXTURE_RGBA;
        step = 4;
        break;
    default:
        return luaL_error(L, "png color type %d not support", color_type);
    } 

    png_bytep *row_pointers = (png_bytep *)malloc(height * sizeof(png_bytep));

    png_size_t rowbytes = png_get_rowbytes(png_ptr,info_ptr);

    size_t bytes = rowbytes * height;
    uint8_t *buffer = (uint8_t *)malloc(bytes);
    int i;
    for (i=0; i<height; ++i) {
        row_pointers[i] = buffer + i*rowbytes;
    }
    
    png_read_image(png_ptr, row_pointers);

    png_read_end(png_ptr, info_ptr);

    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

    free(row_pointers);

    switch (color_type) {
    case PNG_COLOR_TYPE_GRAY:
        lua_pushliteral(L,"GRAY");
        break;
    case PNG_COLOR_TYPE_RGB:
        lua_pushliteral(L,"RGB8");
        break;
    case PNG_COLOR_TYPE_RGBA:
        lua_pushliteral(L,"RGBA8");
        break;
    }
    lua_pushinteger(L,width);
    lua_pushinteger(L,height);
    int n = width * height * step;
    lua_createtable(L,n,0);
    for (i=0; i<n; ++i) {
        lua_pushinteger(L, buffer[i]);
        lua_rawseti(L, -2, i+1);
    }

    free(buffer);
    return 4;
}
Example #2
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;
    int                          timeout;
    ngx_http_lua_co_ctx_t       *coctx;

    ngx_http_lua_udp_connection_t           *uc;
    ngx_http_lua_socket_udp_upstream_t      *u;

    /*
     * TODO: we should probably accept an extra argument to setpeername()
     * to allow the user bind the datagram unix domain socket himself,
     * which is necessary for systems without autobind support.
     */

    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);
    }

    r = ngx_http_lua_get_req(L);
    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
                               | NGX_HTTP_LUA_CONTEXT_TIMER
                               | NGX_HTTP_LUA_CONTEXT_SSL_CERT);

    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, "no 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 > 65535) {
            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->request && u->request != r) {
            return luaL_error(L, "bad request");
        }

        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, "no memory");
        }

#if 1
        lua_pushlightuserdata(L, &ngx_http_lua_udp_udata_metatable_key);
        lua_rawget(L, LUA_REGISTRYINDEX);
        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 = (in_port_t) 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, "no 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;
#if !defined(nginx_version) || nginx_version < 1005008
    rctx->type = NGX_RESOLVE_A;
#endif
    rctx->handler = ngx_http_lua_socket_resolve_handler;
    rctx->data = u;
    rctx->timeout = clcf->resolver_timeout;

    u->co_ctx = ctx->cur_co_ctx;
    u->resolved->ctx = rctx;

    saved_top = lua_gettop(L);

    coctx = ctx->cur_co_ctx;
    ngx_http_lua_cleanup_pending_operation(coctx);
    coctx->cleanup = ngx_http_lua_udp_resolve_cleanup;

    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;

    coctx->data = u;

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

    } else {
        r->write_event_handler = ngx_http_core_run_phases;
    }

    return lua_yield(L, 0);
}
Example #3
0
int CEntityBase::GiveClient(lua_State* L, int fd)
{
	static const string strClient = "client";
	int old_fd = -1;

	ClearLuaStack(L);

	map<string, VOBJECT*>::iterator iter = m_data.lower_bound(strClient);
	if (iter != m_data.end() && iter->first == strClient)
	{

		CWorldBase& the_world = GetWorldbase();
		CLuaCallback& cb = the_world.GetLuaTables();
		int ref = (int)(iter->second->vv.i32);
		cb.GetObj(L, ref);

		LogDebug("CEntityBase::GiveClient", "m_id=%d;ref=%d", m_id, ref);

		if (lua_istable(L, -1))
		{

			lua_rawgeti(L, -1, g_nMailBoxServerIdKey);
			old_fd = (int)lua_tointeger(L, -1);
			//printf("old_fd:%d,new_fd:%d\n", old_fd, fd);
			lua_pop(L, 1);


			lua_pushinteger(L, fd);
			lua_rawseti(L, -2, g_nMailBoxServerIdKey);
		}
	}
	else
	{
		//先用table,以后再改为userdata;table的话可以在lua里修改id,sid等几个值
		NewClientMailbox(L, fd, m_etype, m_id);

		CLuaCallback& cb = GetWorld()->GetLuaTables();
		int nRef = cb.Ref(L);

		LogDebug("CEntityBase::GiveClient", "m_id=%d;nRef=%d", m_id, nRef);

		VOBJECT* v = new VOBJECT;
		v->vt = V_LUATABLE;
		v->vv.i32 = nRef;
		m_data.insert(iter, make_pair("client", v));
	}

	this->SetClientFd(fd);

	m_bHasClient = true;//获得client标记

	//通知客户端attach到entity,并刷所有带CLIENT标记的数据给客户端
	CMailBox* mb = GetWorld()->GetServer()->GetClientMailbox(fd);
	if (mb)
	{
		CPluto* u = new CPluto;
		u->Encode(MSGID_CLIENT_ENTITY_ATTACHED);

#ifdef __RELOGIN
		//客户端一旦登录,则先生成一个key值,用于断线重连时使用
		const string& key = GetWorldbase().MakeClientReLoginKey("", m_id);
		s_clientReLoginKey = key;
		(*u) << key.c_str();
		LogDebug("CEntityBase::GiveClient", "s_clientReLoginKey=%s;m_id=%d", s_clientReLoginKey.c_str(), m_id);
#endif

		if (PickleClientToPluto(*u))
		{
			(*u) << EndPluto;
			mb->PushPluto(u);
			//LogDebug("CEntityBase::GiveClient", "u->GetLen()=%d;", u->GetLen());
		}
		else
		{
			delete u;
		}

		//如果有cell则通知cell同步数据
		this->NotifyCellSyncClientAttris();
	}

	//通知cell刷aoi数据给客户端
	int nCellId = GetCellServerId();
	if (nCellId > 0)
	{
		GetWorld()->RpcCall(nCellId, MSGID_CELLAPP_PICKLE_AOI_ENTITIES, m_id);
	}

	//通知脚本
		{
			//clear_lua_stack(L);
			int _n = EntityMethodCall(L, this, "onClientGetBase", 0, 0);
			lua_pop(L, _n);
		}

		if (old_fd > 0 && old_fd != fd)
		{
			//关闭老的连接
			GetWorldbase().KickOffFd(old_fd);
		}

		return 0;
}
Example #4
0
/* Wrapper for scan list */
static int iwinfo_L_scanlist(lua_State *L, int (*func)(const char *, char *, int *))
{
	int i, x, len = 0;
	char rv[IWINFO_BUFSIZE];
	char macstr[18];
	const char *ifname = luaL_checkstring(L, 1);
	struct iwinfo_scanlist_entry *e;

	lua_newtable(L);
	memset(rv, 0, sizeof(rv));

	if (!(*func)(ifname, rv, &len))
	{
		for (i = 0, x = 1; i < len; i += sizeof(struct iwinfo_scanlist_entry), x++)
		{
			e = (struct iwinfo_scanlist_entry *) &rv[i];

			lua_newtable(L);

			/* BSSID */
			sprintf(macstr, "%02X:%02X:%02X:%02X:%02X:%02X",
				e->mac[0], e->mac[1], e->mac[2],
				e->mac[3], e->mac[4], e->mac[5]);

			lua_pushstring(L, macstr);
			lua_setfield(L, -2, "bssid");

			/* ESSID */
			if (e->ssid[0])
			{
				lua_pushstring(L, (char *) e->ssid);
				lua_setfield(L, -2, "ssid");
			}

			/* Channel */
			lua_pushinteger(L, e->channel);
			lua_setfield(L, -2, "channel");

			/* Mode */
			lua_pushstring(L, IWINFO_OPMODE_NAMES[e->mode]);
			lua_setfield(L, -2, "mode");

			/* Quality, Signal */
			lua_pushinteger(L, e->quality);
			lua_setfield(L, -2, "quality");

			lua_pushinteger(L, e->quality_max);
			lua_setfield(L, -2, "quality_max");

			lua_pushnumber(L, (e->signal - 0x100));
			lua_setfield(L, -2, "signal");

			/* Crypto */
			iwinfo_L_cryptotable(L, &e->crypto);
			lua_setfield(L, -2, "encryption");

			lua_rawseti(L, -2, x);
		}
	}

	return 1;
}
Example #5
0
static int euh_init_keymod_table(lua_State *L)
{
	// str->kmod
	lua_newtable(L);
	// kmod->str
	lua_newtable(L);

	// KMOD_NONE
	lua_pushliteral(L,"none");
	lua_pushinteger(L,KMOD_NONE);
	lua_rawset(L,-3);
	lua_pushliteral(L,"none");
	lua_rawseti(L,-3,KMOD_NONE);
	// KMOD_LSHIFT
	lua_pushliteral(L,"lshift");
	lua_pushinteger(L,KMOD_LSHIFT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"lshift");
	lua_rawseti(L,-3,KMOD_LSHIFT);
	// KMOD_RSHIFT
	lua_pushliteral(L,"rshift");
	lua_pushinteger(L,KMOD_RSHIFT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"rshift");
	lua_rawseti(L,-3,KMOD_RSHIFT);
	// KMOD_LCTRL
	lua_pushliteral(L,"lctrl");
	lua_pushinteger(L,KMOD_LCTRL);
	lua_rawset(L,-3);
	lua_pushliteral(L,"lctrl");
	lua_rawseti(L,-3,KMOD_LCTRL);
	// KMOD_RCTRL
	lua_pushliteral(L,"rctrl");
	lua_pushinteger(L,KMOD_RCTRL);
	lua_rawset(L,-3);
	lua_pushliteral(L,"rctrl");
	lua_rawseti(L,-3,KMOD_RCTRL);
	// KMOD_LALT
	lua_pushliteral(L,"lalt");
	lua_pushinteger(L,KMOD_LALT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"lalt");
	lua_rawseti(L,-3,KMOD_LALT);
	// KMOD_RALT
	lua_pushliteral(L,"ralt");
	lua_pushinteger(L,KMOD_RALT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"ralt");
	lua_rawseti(L,-3,KMOD_RALT);
	// KMOD_LGUI
	lua_pushliteral(L,"lgui");
	lua_pushinteger(L,KMOD_LGUI);
	lua_rawset(L,-3);
	lua_pushliteral(L,"lgui");
	lua_rawseti(L,-3,KMOD_LGUI);
	// KMOD_RGUI
	lua_pushliteral(L,"rgui");
	lua_pushinteger(L,KMOD_RGUI);
	lua_rawset(L,-3);
	lua_pushliteral(L,"rgui");
	lua_rawseti(L,-3,KMOD_RGUI);
	// KMOD_NUM
	lua_pushliteral(L,"num");
	lua_pushinteger(L,KMOD_NUM);
	lua_rawset(L,-3);
	lua_pushliteral(L,"num");
	lua_rawseti(L,-3,KMOD_NUM);
	// KMOD_CAPS
	lua_pushliteral(L,"caps");
	lua_pushinteger(L,KMOD_CAPS);
	lua_rawset(L,-3);
	lua_pushliteral(L,"caps");
	lua_rawseti(L,-3,KMOD_CAPS);
	// KMOD_MODE
	lua_pushliteral(L,"mode");
	lua_pushinteger(L,KMOD_MODE);
	lua_rawset(L,-3);
	lua_pushliteral(L,"mode");
	lua_rawseti(L,-3,KMOD_MODE);
	// KMOD_CTRL
	lua_pushliteral(L,"ctrl");
	lua_pushinteger(L,KMOD_CTRL);
	lua_rawset(L,-3);
	lua_pushliteral(L,"ctrl");
	lua_rawseti(L,-3,KMOD_CTRL);
	// KMOD_SHIFT
	lua_pushliteral(L,"shift");
	lua_pushinteger(L,KMOD_SHIFT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"shift");
	lua_rawseti(L,-3,KMOD_SHIFT);
	// KMOD_ALT
	lua_pushliteral(L,"alt");
	lua_pushinteger(L,KMOD_ALT);
	lua_rawset(L,-3);
	lua_pushliteral(L,"alt");
	lua_rawseti(L,-3,KMOD_ALT);
	// KMOD_GUI
	lua_pushliteral(L,"gui");
	lua_pushinteger(L,KMOD_GUI);
	lua_rawset(L,-3);
	lua_pushliteral(L,"gui");
	lua_rawseti(L,-3,KMOD_GUI);

	lua_setfield(L, LUA_REGISTRYINDEX, EU_STR_TO_KEYMOD_TBL);
	lua_setfield(L, LUA_REGISTRYINDEX, EU_KEYMOD_TO_STR_TBL);
	return 0;
}
int lua_field_spots(lua_State *L) {
  std::vector<RegionProps> props;

  uint8_t *im_ptr = (uint8_t *) lua_touserdata(L, 1);
  if ((im_ptr == NULL) || !lua_islightuserdata(L, 1)) {
    return luaL_error(L, "Input image not light user data");
  }
  int m = luaL_checkint(L, 2);
  int n = luaL_checkint(L, 3);

  int nlabel = ConnectRegions(props, im_ptr, m, n, colorSpot);
  if (nlabel <= 0) {
    return 0;
  }

  std::vector<int> valid;
  for (int i = 0; i < nlabel; i++) {
    if (CheckBoundary(props[i], im_ptr, m, n, colorField)) {
      valid.push_back(i);
    }
  }
  int nvalid = valid.size();
  if (nvalid < 1) {
    return 0;
  }

  lua_createtable(L, nvalid, 0);
  for (int i = 0; i < nvalid; i++) {
    lua_createtable(L, 0, 3);
    // area field
    lua_pushstring(L, "area");
    lua_pushnumber(L, props[valid[i]].area);
    lua_settable(L, -3);

    // centroid field
    lua_pushstring(L, "centroid");
    double centroidI = (double)props[valid[i]].sumI/props[valid[i]].area;
    double centroidJ = (double)props[valid[i]].sumJ/props[valid[i]].area;
    lua_createtable(L, 2, 0);
    lua_pushnumber(L, centroidI);
    lua_rawseti(L, -2, 1);
    lua_pushnumber(L, centroidJ);
    lua_rawseti(L, -2, 2);
    lua_settable(L, -3);

    // boundingBox field
    lua_pushstring(L, "boundingBox");
    lua_createtable(L, 4, 0);
    lua_pushnumber(L, props[valid[i]].minI);
    lua_rawseti(L, -2, 1);
    lua_pushnumber(L, props[valid[i]].maxI);
    lua_rawseti(L, -2, 2);
    lua_pushnumber(L, props[valid[i]].minJ);
    lua_rawseti(L, -2, 3);
    lua_pushnumber(L, props[valid[i]].maxJ);
    lua_rawseti(L, -2, 4);
    lua_settable(L, -3);

    lua_rawseti(L, -2, i+1);
  }
  return 1;
}
/* Set arguments using the same fit parameters as have been used */
static int luaDefaultSetBGStreamParametersFromArguments(lua_State* luaSt)
{
    int i, ptable, bgTable, streamTable, n, nStream, idx, thisStream;

    ptable = mw_lua_checktable(luaSt, lua_gettop(luaSt));
    n = luaL_getn(luaSt, ptable);  /* Number parameters */

    /* Set background parameters */
    lua_newtable(luaSt);
    bgTable = lua_gettop(luaSt);
    lua_pushvalue(luaSt, bgTable);
    lua_setglobal(luaSt, BACKGROUND_NAME);

    bgTable = lua_gettop(luaSt);

    lua_rawgeti(luaSt, ptable, 1);
    lua_setfield(luaSt, bgTable, "q");

    lua_rawgeti(luaSt, ptable, 2);
    lua_setfield(luaSt, bgTable, "r0");

    /* Not included in fit */
    lua_pushnumber(luaSt, 0.0);
    lua_setfield(luaSt, bgTable, "epsilon");

    lua_pushnumber(luaSt, 1.0);
    lua_setfield(luaSt, bgTable, "alpha");

    lua_pushnumber(luaSt, 1.0);
    lua_setfield(luaSt, bgTable, "delta");

    lua_pop(luaSt, 1);


    /* Set stream parameters */
    lua_newtable(luaSt);
    streamTable = lua_gettop(luaSt);
    lua_pushvalue(luaSt, streamTable);
    lua_setglobal(luaSt, STREAMS_NAME);

    streamTable = lua_gettop(luaSt);

    if (!mwDivisible(n - NUMBER_FIT_BG_PARAMETERS, NUMBER_FIT_STREAM_PARAMETERS))
    {
        return luaL_error(luaSt, "Parameter count (%d) inconsistent with default argument mapping\n", n);
    }

    nStream = (n - NUMBER_FIT_BG_PARAMETERS) / NUMBER_FIT_STREAM_PARAMETERS;

    for (i = 0; i < nStream; ++i)
    {
        lua_newtable(luaSt);
        thisStream = lua_gettop(luaSt);
        idx = NUMBER_FIT_BG_PARAMETERS + i * NUMBER_FIT_STREAM_PARAMETERS;

        lua_rawgeti(luaSt, ptable, idx + 1);
        lua_setfield(luaSt, thisStream, "epsilon");

        lua_rawgeti(luaSt, ptable, idx + 2);
        lua_setfield(luaSt, thisStream, "mu");

        lua_rawgeti(luaSt, ptable, idx + 3);
        lua_setfield(luaSt, thisStream, "r");

        lua_rawgeti(luaSt, ptable, idx + 4);
        lua_setfield(luaSt, thisStream, "theta");

        lua_rawgeti(luaSt, ptable, idx + 5);
        lua_setfield(luaSt, thisStream, "phi");

        lua_rawgeti(luaSt, ptable, idx + 6);
        lua_setfield(luaSt, thisStream, "sigma");

        mw_lua_assert_top_type(luaSt, LUA_TTABLE);

        lua_rawseti(luaSt, streamTable, i + 1);
    }

    lua_pop(luaSt, 1);
    return 0;
}
Example #8
0
int luvit_init(lua_State *L, uv_loop_t* loop, int argc, char *argv[])
{
  int index, rc;
  ares_channel channel;
  struct ares_options options;

  luvit__suck_in_symbols();

  memset(&options, 0, sizeof(options));

  rc = ares_library_init(ARES_LIB_INIT_ALL);
  assert(rc == ARES_SUCCESS);

  // Pull up the preload table
  lua_getglobal(L, "package");
  lua_getfield(L, -1, "preload");
  lua_remove(L, -2);

  // Register yajl
  lua_pushcfunction(L, luaopen_yajl);
  lua_setfield(L, -2, "yajl");
  // Register os
  lua_pushcfunction(L, luaopen_os_binding);
  lua_setfield(L, -2, "os_binding");
  // Register http_parser
  lua_pushcfunction(L, luaopen_http_parser);
  lua_setfield(L, -2, "http_parser");
  // Register uv
  lua_pushcfunction(L, luaopen_uv);
  lua_setfield(L, -2, "uv");
  // Register env
  lua_pushcfunction(L, luaopen_env);
  lua_setfield(L, -2, "env");
  // Register constants
  lua_pushcfunction(L, luaopen_constants);
  lua_setfield(L, -2, "constants");

  // We're done with preload, put it away
  lua_pop(L, 1);

  // Get argv
  lua_createtable (L, argc, 0);
  for (index = 0; index < argc; index++) {
    lua_pushstring (L, argv[index]);
    lua_rawseti(L, -2, index);
  }
  lua_setglobal(L, "argv");

  lua_pushcfunction(L, luvit_exit);
  lua_setglobal(L, "exit_process");

  lua_pushcfunction(L, luvit_print_stderr);
  lua_setglobal(L, "print_stderr");

  lua_pushcfunction(L, luvit_getcwd);
  lua_setglobal(L, "getcwd");

  lua_pushstring(L, LUVIT_VERSION);
  lua_setglobal(L, "VERSION");

  lua_pushstring(L, UV_VERSION);
  lua_setglobal(L, "UV_VERSION");
  
  lua_pushstring(L, LUAJIT_VERSION);
  lua_setglobal(L, "LUAJIT_VERSION");

  lua_pushstring(L, HTTP_VERSION);
  lua_setglobal(L, "HTTP_VERSION");

  lua_pushstring(L, YAJL_VERSIONISH);
  lua_setglobal(L, "YAJL_VERSION");

  // Hold a reference to the main thread in the registry
  assert(lua_pushthread(L) == 1);
  lua_setfield(L, LUA_REGISTRYINDEX, "main_thread");

  // Store the loop within the registry
  luv_set_loop(L, loop);

  // Store the ARES Channel
  uv_ares_init_options(luv_get_loop(L), &channel, &options, 0);
  luv_set_ares_channel(L, &channel);

  return 0;
}
Example #9
0
static void lluv_on_getaddrinfo(uv_getaddrinfo_t* arg, int status, struct addrinfo* res){
  lluv_req_t  *req   = lluv_req_byptr((uv_req_t*)arg);
  lluv_loop_t *loop  = lluv_loop_byptr(arg->loop);
  lua_State   *L     = loop->L;
  struct addrinfo* a = res;
  int i = 0;

  LLUV_CHECK_LOOP_CB_INVARIANT(L);

  lua_rawgeti(L, LLUV_LUA_REGISTRY, req->cb);
  lluv_req_free(L, req);
  assert(!lua_isnil(L, -1));

  lluv_loop_pushself(L, loop);

  if(status < 0){
    uv_freeaddrinfo(res);
    lluv_error_create(L, LLUV_ERR_UV, (uv_errno_t)status, NULL);
    LLUV_LOOP_CALL_CB(L, loop, 2);
    LLUV_CHECK_LOOP_CB_INVARIANT(L);
    return;
  }

  lua_pushnil(L);
  lua_newtable(L);
  for(a = res; a; a = a->ai_next){
    char buf[INET6_ADDRSTRLEN + 1];
    int port;
    lua_newtable(L);

    switch (a->ai_family){
      case AF_INET:{
        struct sockaddr_in *sa = (struct sockaddr_in*)a->ai_addr;
        uv_ip4_name(sa, buf, sizeof(buf));
        lua_pushstring(L, buf);
        lua_setfield(L, -2, "address");
        if((port = ntohs(sa->sin_port))){
          lua_pushinteger(L, port);
          lua_setfield(L, -2, "port");
        }
        break;
      }

      case AF_INET6:{
        struct sockaddr_in6 *sa = (struct sockaddr_in6*)a->ai_addr;
        uv_ip6_name(sa, buf, sizeof(buf));
        lua_pushstring(L, buf);
        lua_setfield(L, -2, "address");
        if((port = ntohs(sa->sin6_port))){
          lua_pushinteger(L, port);
          lua_setfield(L, -2, "port");
        }
        break;
      }
    }

    if(a->ai_canonname){
      lua_pushstring(L, a->ai_canonname);
      lua_setfield(L, -2, "canonname");
    }

    lluv_push_ai_family(L, a->ai_family);
    lua_setfield(L, -2, "family");

    lluv_push_ai_stype(L, a->ai_socktype);
    lua_setfield(L, -2, "socktype");

    lluv_push_ai_proto(L, a->ai_protocol);
    lua_setfield(L, -2, "protocol");

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

  uv_freeaddrinfo(res);
  LLUV_LOOP_CALL_CB(L, loop, 3);

  LLUV_CHECK_LOOP_CB_INVARIANT(L);
}
Example #10
0
static void
_push_array(lua_State *L, pbc_array array, char type, int index) {
	switch (type) {
	case 'I': {
		int v = pbc_array_integer(array, index, NULL);
		lua_pushinteger(L, v);
		break;
	}
	case 'U': {
		uint32_t hi = 0;
		uint32_t low = pbc_array_integer(array, index, &hi);
		uint64_t v = (uint64_t)hi << 32 | (uint64_t)low;
		lua_pushnumber(L, (lua_Number)v);
		break;
	}
	case 'D': {
		uint32_t hi = 0;
		uint32_t low = pbc_array_integer(array, index, &hi);
		uint64_t v = (uint64_t)hi << 32 | (uint64_t)low;
		lua_pushnumber(L, (lua_Number)((int64_t)v));
		break;
	}
	case 'B': {
		int v = pbc_array_integer(array, index, NULL);
		lua_pushboolean(L, v);
		break;
	}
	case 'P': {
		uint32_t v = pbc_array_integer(array, index, NULL);
		lua_pushlightuserdata(L,(void *)(intptr_t)v);
		break;
	}
	case 'X': {
		uint32_t hi = 0;
		uint32_t low = pbc_array_integer(array, index, &hi);
		uint64_t v = (uint64_t)low | (uint64_t)hi << 32;
		lua_pushlstring(L, (char *)&v, 8);
		break;
	}
	case 'R': {
		double v = pbc_array_real(array, index);
		lua_pushnumber(L, v);
		break;
	}
	case 'S': {
		struct pbc_slice * slice = pbc_array_slice(array, index);
		lua_pushlstring(L, (const char *)slice->buffer,slice->len);
		break;
	}
	case 'M': {
		struct pbc_slice * slice = pbc_array_slice(array, index);
		lua_createtable(L,2,0);
		lua_pushlightuserdata(L,slice->buffer);
		lua_rawseti(L,-2,1);
		lua_pushinteger(L,slice->len);
		lua_rawseti(L,-2,2);
		break;
	}
	}
	lua_rawseti(L,-2,index+1);
}
Example #11
0
File: seed.c Project: Chingliu/seed
int main(int argc, char ** argv)
{
    // number of arguments to skip before the script's real arguments
    int skip_arg = 1;

    // init physfs
    if(!PHYSFS_init(argv[0]))
    {
        fprintf(stderr, "physfs init failed: %s", PHYSFS_getLastError());
        return 1;
    }

    // get executable path
    const char *directory = PHYSFS_getBaseDir();
    const char *executable = basename(argv[0]);
    char *path = malloc(strlen(directory) + strlen(executable) + 1);
    strcpy(path, directory);
    strcat(path, executable);
    // try to mount the executable as an archive, on failure try to mount the
    // first argument instead
    if(!PHYSFS_mount(path, "/", 0))
    {
        skip_arg = skip_arg + 1;
        if(argc < 2 || !PHYSFS_mount(argv[1], "/", 0))
        {
            fprintf(stderr, "no archive found in the executable nor in the "
                    "first argument\n");
            return 1;
        }
    }
    free(path);

    // load lua and libraries
    lua_State *L = lua_open();
    luaL_openlibs(L);
    init_physfs_loader(L);
    init_preloaders(L);
    
    // load arguments (and pre-arguments) into a global 'arg' table
    lua_newtable(L);
    for(int i = 0; i < argc; i++)
    {
        lua_pushstring(L, argv[i]);
        lua_rawseti(L, -2, i - skip_arg + 1);
    }
    lua_setglobal(L, "arg");

    // open app, with error reporting
    lua_getglobal(L, "debug");
    lua_getfield(L, -1, "traceback");

    lua_pushcfunction(L, seed_loadfile);
    lua_pushstring(L, "init.lua");
    int error = lua_pcall(L, 1, 1, 0); // load file

    if(!error)
    {
        // load command-line arguments as function arguments
        lua_checkstack(L, argc - skip_arg);
        for(int i = 1; i <= argc - skip_arg; i++)
            lua_pushstring(L, argv[i + skip_arg - 1]);
        error = lua_pcall(L, argc - skip_arg, 0, -2);  // run the result
    }

    if(error)
        fprintf(stderr, "%s\n", lua_tostring(L, -1));

    lua_close(L);
    PHYSFS_deinit();
    return error;
}
Example #12
0
static void *
_push_value(lua_State *L, char * ptr, char type) {
	switch(type) {
		case 'u': {
			uint64_t v = *(uint64_t*)ptr;
			ptr += 8;
			lua_pushnumber(L,(lua_Number)v);
			break;
		}
		case 'i': {
			int32_t v = *(int32_t*)ptr;
			ptr += 4;
			lua_pushinteger(L,v);
			break;
		}
		case 'b': {
			int32_t v = *(int32_t*)ptr;
			ptr += 4;
			lua_pushboolean(L,v);
			break;
		}
		case 'p': {
			uint32_t v = *(uint32_t*)ptr;
			ptr += 4;
			lua_pushlightuserdata(L,(void *)(intptr_t)v);
			break;
		}
		case 'x': {
			lua_pushlstring(L,ptr,8);
			ptr += 8;
			break;
		}
		case 'd': {
			int64_t v = *(int64_t*)ptr;
			ptr += 8;
			lua_pushnumber(L,(lua_Number)v);
			break;
		}
		case 'r': {
			double v = *(double *)ptr;
			ptr += 8;
			lua_pushnumber(L,v);
			break;
		}
		case 's': {
			struct pbc_slice * slice = (struct pbc_slice *)ptr;
			lua_pushlstring(L,(const char *)slice->buffer, slice->len);
			ptr += sizeof(struct pbc_slice);
			break;
		}
		case 'm': {
			struct pbc_slice * slice = (struct pbc_slice *)ptr;
			lua_createtable(L,2,0);
			lua_pushlightuserdata(L, slice->buffer);
			lua_rawseti(L,-2,1);
			lua_pushinteger(L,slice->len);
			lua_rawseti(L,-2,2);
			ptr += sizeof(struct pbc_slice);
			break;			
		}
	}
	return ptr;
}
Example #13
0
int EventDispatcherBinder::addEventListener(lua_State* L)
{
	StackChecker checker(L, "EventDispatcherBinder::addEventListener", 0);

	Binder binder(L);
	EventDispatcher* eventDispatcher = static_cast<EventDispatcher*>(binder.getInstance("EventDispatcher", 1));

	luaL_checktype(L, 2, LUA_TSTRING);
	luaL_checktype(L, 3, LUA_TFUNCTION);

    bool hasData = !lua_isnoneornil(L, 4);

	createEventsTable(L, 1);	// create self.__events table if it's not created

	EventBinderMap& map = getOrCreateEventBinderMap(eventDispatcher);

	const char* event = lua_tostring(L, 2);
	int eventid = StringId::instance().id(event);

	const std::vector<CppLuaBridge*>& bridges = map[eventid]; 

	lua_getfield(L, 1, "__events");		// key is CppLuaBridge*, value is 'event check closure'

	// check if the event is already registered
	bool isFound = false;
	for (std::size_t i = 0; i < bridges.size(); ++i)
	{
		lua_pushlightuserdata(L, bridges[i]);
		lua_rawget(L, -2);	// we get the event check closure
		if (hasData == false)
		{
			lua_pushvalue(L, 3);	// function
			lua_call(L, 1, 1);
		}
		else
		{
			lua_pushvalue(L, 3);	// function
			lua_pushvalue(L, 4);	// data
			lua_call(L, 2, 1);
		}

		if (lua_toboolean(L, -1))
		{
			lua_pop(L, 1);
			isFound = true;
			break;
		}
		else
			lua_pop(L, 1);
	}

	if (isFound == true)
	{
		lua_pop(L, 1);		// pop __events, leave stack as it is
		return 0;
	}

    LuaApplication *application = (LuaApplication*)luaL_getdata(L);
    lua_State *mainL = application->getLuaState();

    CppLuaBridge* bridge = new CppLuaBridge(mainL);

	// create event closure
	luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);
	lua_pushlightuserdata(L, bridge);	// key=bridge
	if (hasData == false)				// value=closure
	{
        // self ve function'in eventClosure'in icine upvalue olarak koyulmasi garbage collect edilmesini engelliyor
        // bu yuzden {self, function} seklinde bi weak table yaratip ilk upvalue olarak onu set ediyoruz
		luaL_newweaktable(L);

        lua_pushvalue(L, 1);	// self
		lua_rawseti(L, -2, 1);

		lua_pushvalue(L, 3);	// function
        lua_rawseti(L, -2, 2);

        lua_pushcclosure(L, &eventClosure, 1);
	}
	else
	{
        // self, function ve data'nin eventClosure'in icine upvalue olarak koyulmasi garbage collect edilmesini engelliyor
        // bu yuzden {self, function, data} seklinde bi weak table yaratip ilk upvalue olarak onu set ediyoruz
		luaL_newweaktable(L);

        lua_pushvalue(L, 1);	// self
		lua_rawseti(L, -2, 1);

        lua_pushvalue(L, 3);	// function
        lua_rawseti(L, -2, 2);

        lua_pushvalue(L, 4);	// data
        lua_rawseti(L, -2, 3);

        lua_pushcclosure(L, &eventClosureWithData, 1);
	}
	lua_rawset(L, -3);					// envtable["eventClosures"][bridge] = closure
	lua_pop(L, 1);						// pop envtable["eventClosures"]

	// create event check closure
	lua_pushlightuserdata(L, bridge);
	if (hasData == false)
	{
		lua_pushvalue(L, 3);	// function
		lua_pushcclosure(L, &eventCheckClosure, 1);
	}
	else
	{
		lua_pushvalue(L, 3);	// function
		lua_pushvalue(L, 4);	// data
		lua_pushcclosure(L, &eventCheckClosureWithData, 2);
	}
	lua_rawset(L, -3);
	
	map.push_back(eventid, bridge);

	bridge->unref();
	
	eventDispatcher->addEventListener(LuaEvent::Type(event), bridge, &CppLuaBridge::luaEvent);

	lua_pop(L, 1);			// pop __events, leave stack as it is

	return 0;
}
Example #14
0
	virtual void visit(TouchEvent* v)
	{
		StackChecker checker(L, "visit(TouchEvent* v)", 0);

		Binder binder(L);

		// get closure
		luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);
		lua_pushlightuserdata(L, bridge_);
		lua_rawget(L, -2);
		lua_remove(L, -2);		// remove env["eventClosures"]

		luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_TouchEvent);

		lua_getfield(L, -1, "__uniqueid");

		if (lua_isnil(L, -1) || lua_tointeger(L, -1) != v->uniqueid())
		{
			lua_pop(L, 1);

			lua_pushinteger(L, v->uniqueid());
			lua_setfield(L, -2, "__uniqueid");

			binder.setInstance(-1, v);

			lua_pushstring(L, v->type()); // TODO: buna artik ihtiyac yok. direk Event'te getType() fonksiyonu var
			lua_setfield(L, -2, "type");

            // touch
            getOrCreateTouch(&v->event->touch, v->sx, v->sy, v->tx, v->ty);
            lua_setfield(L, -2, "touch");

            // touches (it has only 1 element)
			lua_getfield(L, -1, "touches");
			if (lua_isnil(L, -1))
			{
				lua_pop(L, 1);
				lua_newtable(L);
			}
			else
			{
				int n = lua_objlen(L, -1);
				for (int i = n; i >= 1; --i)
				{
					lua_pushnil(L);
					lua_rawseti(L, -2, i);
				}
			}
            getOrCreateTouch(&v->event->touch, v->sx, v->sy, v->tx, v->ty);
            lua_rawseti(L, -2, 1);
			lua_setfield(L, -2, "touches");

            // allTouches
			lua_getfield(L, -1, "allTouches");
			if (lua_isnil(L, -1))
			{
				lua_pop(L, 1);
				lua_newtable(L);
			}
			else
			{
				int n = lua_objlen(L, -1);
				for (int i = n; i >= 1; --i)
				{
					lua_pushnil(L);
					lua_rawseti(L, -2, i);
				}
			}
            for (std::size_t i = 0; i < v->event->allTouchesCount; ++i)
			{
                getOrCreateTouch(&v->event->allTouches[i], v->sx, v->sy, v->tx, v->ty);
                lua_rawseti(L, -2, i + 1);
			}
			lua_setfield(L, -2, "allTouches");
		}
		else
		{
			lua_pop(L, 1);
		}
		
		lua_call(L, 1, 0);
	}
Example #15
0
static void set2 (lua_State *L, int i, int j) {
  lua_rawseti(L, 1, i);
  lua_rawseti(L, 1, j);
}
Example #16
0
/* Embedded code is not funny at all... */
int
mib_instance_search(struct oid_search_res *ret_oid)
{
  int i;
  Variable *var = &ret_oid->var;
  lua_State *L = mib_lua_state;

  /* Empty lua stack. */
  lua_pop(L, -1);
  /* Get function. */
  lua_rawgeti(L, LUA_ENVIRONINDEX, ret_oid->callback);
  /* op */
  lua_pushinteger(L, ret_oid->request);
  /* req_sub_oid */
  lua_newtable(L);
  for (i = 0; i < ret_oid->inst_id_len; i++) {
    lua_pushinteger(L, ret_oid->inst_id[i]);
    lua_rawseti(L, -2, i + 1);
  }

  if (ret_oid->request == SNMP_REQ_SET) {
    /* req_val */
    switch (tag(var)) {
    case ASN1_TAG_INT:
      lua_pushinteger(L, integer(var));
      break;
    case ASN1_TAG_OCTSTR:
      lua_pushlstring(L, octstr(var), length(var));
      break;
    case ASN1_TAG_CNT:
      lua_pushnumber(L, count(var));
      break;
    case ASN1_TAG_IPADDR:
      lua_pushlstring(L, (char *)ipaddr(var), length(var));
      break;
    case ASN1_TAG_OBJID:
      lua_newtable(L);
      for (i = 0; i < length(var); i++) {
        lua_pushnumber(L, oid(var)[i]);
        lua_rawseti(L, -2, i + 1);
      }
      break;
    case ASN1_TAG_GAU:
      lua_pushnumber(L, gauge(var));
      break;
    case ASN1_TAG_TIMETICKS:
      lua_pushnumber(L, timeticks(var));
      break;
    default:
      lua_pushnil(L);
      break;
    }
    /* req_val_type */
    lua_pushinteger(L, tag(var));
  } else {
    /* req_val */
    lua_pushnil(L);
    /* req_val_type */
    lua_pushnil(L);
  }

  if (lua_pcall(L, 4, 4, 0) != 0) {
    SMARTSNMP_LOG(L_ERROR, "MIB search hander %d fail: %s\n", ret_oid->callback, lua_tostring(L, -1));
    tag(var) = ASN1_TAG_NO_SUCH_OBJ;
    return 0;
  }

  ret_oid->err_stat = lua_tointeger(L, -4);
  tag(var) = lua_tonumber(L, -1);

  if (!ret_oid->err_stat && ASN1_TAG_VALID(tag(var))) {
    /* Return value */
    if (ret_oid->request != SNMP_REQ_SET) {
      switch (tag(var)) {
      case ASN1_TAG_INT:
        length(var) = 1;
        integer(var) = lua_tointeger(L, -2);
        break;
      case ASN1_TAG_OCTSTR:
        length(var) = lua_objlen(L, -2);
        memcpy(octstr(var), lua_tostring(L, -2), length(var));
        break;
      case ASN1_TAG_CNT:
        length(var) = 1;
        count(var) = lua_tonumber(L, -2);
        break;
      case ASN1_TAG_IPADDR:
        length(var) = lua_objlen(L, -2);
        for (i = 0; i < length(var); i++) {
          lua_rawgeti(L, -2, i + 1);
          ipaddr(var)[i] = lua_tointeger(L, -1);
          lua_pop(L, 1);
        }
        break;
      case ASN1_TAG_OBJID:
        length(var) = lua_objlen(L, -2);
        for (i = 0; i < length(var); i++) {
          lua_rawgeti(L, -2, i + 1);
          oid(var)[i] = lua_tointeger(L, -1);
          lua_pop(L, 1);
        }
        break;
      case ASN1_TAG_GAU:
        length(var) = 1;
        gauge(var) = lua_tonumber(L, -2);
        break;
      case ASN1_TAG_TIMETICKS:
        length(var) = 1;
        timeticks(var) = lua_tonumber(L, -2);
        break;
      default:
        assert(0);
      }
    }

    /* For GETNEXT request, return the new oid */
    if (ret_oid->request == SNMP_REQ_GETNEXT) {
      ret_oid->inst_id_len = lua_objlen(L, -3);
      for (i = 0; i < ret_oid->inst_id_len; i++) {
        lua_rawgeti(L, -3, i + 1);
        ret_oid->inst_id[i] = lua_tointeger(L, -1);
        lua_pop(L, 1);
      }
    }
  }

  return ret_oid->err_stat;
}
int LuaJavaBridge::CallInfo::pushReturnValue(lua_State *L)
{
	if (m_error != LUAJ_ERR_OK)
	{
		lua_pushinteger(L, m_error);
		return 1;
	}

	switch (m_returnType)
	{
		case TypeInteger:
			lua_pushinteger(L, m_ret.intValue);
			return 1;
		case TypeFloat:
			lua_pushnumber(L, m_ret.floatValue);
			return 1;
		case TypeBoolean:
			lua_pushboolean(L, m_ret.boolValue);
			return 1;
		case TypeString:
			lua_pushstring(L, m_ret.stringValue->c_str());
			return 1;
        case TypeVector:
        {
            lua_newtable(L);
            vector<string> vec = jVector2stdVector(m_env, m_ret.objectValue);
            for (int i=0; i<vec.size(); ++i)
            {
                string s = vec[i];
                int len = lua_objlen(L, -1);
                lua_pushstring(L, s.c_str());
                lua_rawseti(L, -2, len+1);
            }
            return 1;
        }
        case TypeArrayList:
        {
            lua_newtable(L);
            vector<string> vec = jArray2stdVector(m_env, m_ret.objectValue);
            for (int i=0; i<vec.size(); ++i)
            {
                string s = vec[i];
                int len = lua_objlen(L, -1);
                lua_pushstring(L, s.c_str());
                lua_rawseti(L, -2, len+1);
            }
            return 1;
        }
        case TypeMap:
        {
            lua_newtable(L);
            map<string, string> ma = jHashMap2StdMap(m_env, m_ret.objectValue);
            for(map<string, string>::iterator it=ma.begin(); it!=ma.end(); ++it)
            {
                lua_pushstring(L, it->first.c_str());
                lua_pushstring(L, it->second.c_str());
                lua_rawset(L, -3);
            }
            return 1;
        }
	}

	return 0;
}
Example #18
0
static int newpackage(lua_State* L)
{
	int count, i;

	lua_newtable(L);

	/* Add this package to the master list in the registry */
	lua_getregistry(L);
	lua_pushstring(L, "packages");
	lua_gettable(L, -2);
	count = luaL_getn(L, -1);

	lua_pushvalue(L, -3);
	lua_rawseti(L, -2, count + 1);

	lua_pop(L, 2);

	/* Set default values */
	if (count == 0)
	{
		lua_getglobal(L, "project");
		lua_pushstring(L, "name");
		lua_pushstring(L, "name");
		lua_gettable(L, -3);
		lua_settable(L, -4);
		lua_pop(L, 1);
	}
	else
	{
		lua_pushstring(L, "name");
		lua_pushstring(L, "Package");
		lua_pushnumber(L, count);
		lua_concat(L, 2);
		lua_settable(L, -3);
	}

	lua_pushstring(L, "script");
	lua_pushstring(L, currentScript);
	lua_settable(L, -3);

	lua_pushstring(L, "path");
	lua_pushstring(L, path_getdir(currentScript));
	lua_settable(L, -3);

	lua_pushstring(L, "language");
	lua_pushstring(L, "c++");
	lua_settable(L, -3);

	lua_pushstring(L, "kind");
	lua_pushstring(L, "exe");
	lua_settable(L, -3);

	lua_pushstring(L, "objdir");
	lua_pushstring(L, "obj");
	lua_settable(L, -3);

	buildNewConfig(NULL);

	/* Build list of configurations matching what is in the project, and
	 * which can be indexed by name or number */
	lua_pushstring(L, "config");
	lua_newtable(L);

	lua_getglobal(L, "project");
	lua_pushstring(L, "configs");
	lua_gettable(L, -2);
	count = luaL_getn(L, -1);
	
	for (i = 1; i <= count; ++i)
	{
		lua_rawgeti(L, -1, i);

		lua_newtable(L);

		buildNewConfig(lua_tostring(L, -2));
	
		lua_pushvalue(L, -1);
		lua_rawseti(L, -6, i);
		lua_settable(L, -5);
	}

	lua_pop(L, 2);

	/* Hook the index metamethod so I can dynamically add file configs */
	lua_newtable(L);
	lua_pushstring(L, "__index");
	lua_pushcfunction(L, newfileconfig);
	lua_settable(L, -3);
	lua_setmetatable(L, -2);

	/* Set the 'package' global to point to it */
	lua_pushvalue(L, -1);
	lua_setglobal(L, "package");

	lua_settable(L, -3);

	return 1;
}
Example #19
0
/*
 * Arguments: evq_udata,
 *	obj_udata | signal (number),
 *	events (string: "r", "w") | event_flags (number),
 *	callback (function | coroutine),
 *	[timeout (milliseconds), one_shot (boolean)]
 * Returns: [ev_ludata]
 */
static int
levq_add (lua_State *L)
{
  struct event_queue *evq = checkudata(L, 1, EVQ_TYPENAME);
  unsigned int ev_flags = lua_tointeger(L, 3)
   | (lua_toboolean(L, 6) ? EVENT_ONESHOT : 0);
  const msec_t timeout = lua_isnoneornil(L, 5)
   ? TIMEOUT_INFINITE : (msec_t) lua_tointeger(L, 5);
  struct event *ev;
  int res;

#undef ARG_LAST
#define ARG_LAST	4

  ev = levq_new_event(evq);

  if (!(ev_flags & EVENT_TIMER)) {
    fd_t *fdp = lua_touserdata(L, 2);
    ev->fd = fdp ? *fdp
     : (fd_t) (size_t) lua_tointeger(L, 2);  /* signo */
  }

  if (!(ev_flags & (EVENT_READ | EVENT_WRITE))) {
    const char *evstr = lua_tostring(L, 3);

    ev_flags |= (!evstr || evstr[0] == 'r')
     ? EVENT_READ : EVENT_WRITE;
  }

  switch (lua_type(L, 4)) {
  case LUA_TFUNCTION:
    ev_flags |= EVENT_CALLBACK;
    break;
  case LUA_TTHREAD:
    ev_flags |= EVENT_CALLBACK | EVENT_CALLBACK_CORO;
    break;
  }

  ev->flags = ev_flags;

  /* reserve place for timeout_queue */
  if (!evq->ev_free)
    evq->ev_free = levq_new_event(evq);

  if (ev_flags & EVENT_TIMER) {
    res = evq_add_timer(evq, ev, timeout);
  } else {
    if (ev_flags & EVENT_DIRWATCH) {
      const char *path = luaL_checkstring(L, 2);
      res = evq_add_dirwatch(evq, ev, path);
    } else {
      res = evq_add(evq, ev);
    }

    if (!res && timeout != TIMEOUT_INFINITE) {
      evq_set_timeout(ev, timeout);
    }
  }
  if (!res) {
    lua_State *NL = evq->L;
    const int ev_id = ev->ev_id;

    /* cb_fun */
    if (ev_flags & EVENT_CALLBACK) {
      lua_settop(L, 4);
      lua_xmove(L, NL, 1);
      lua_rawseti(NL, EVQ_CORO_CALLBACK, ev_id);
    }
    /* obj_udata */
    lua_settop(L, 2);
    lua_xmove(L, NL, 1);
    lua_rawseti(NL, EVQ_CORO_UDATA, ev_id);

    lua_pushlightuserdata(L, ev);
    return 1;
  }
  levq_del_event(evq, ev);
  return sys_seterror(L, 0);
}
Example #20
0
// 1 string data
// 2 result document table
// return boolean succ (false -> request id, error document)
//	number request_id
//  document first
//	string cursor_id
//  integer startfrom
static int
op_reply(lua_State *L) {
	size_t data_len = 0;
	const char * data = luaL_checklstring(L,1,&data_len);
	struct {
//		int32_t length; // total message size, including this
		int32_t request_id; // identifier for this message
		int32_t response_id; // requestID from the original request
							// (used in reponses from db)
		int32_t opcode; // request type 
		int32_t flags;
		int32_t cursor_id[2];
		int32_t starting;
		int32_t number;
	} const *reply = (const void *)data;

	if (data_len < sizeof(*reply)) {
		lua_pushboolean(L, 0);
		return 1;
	}

	int id = to_little_endian(reply->response_id);
	int flags = to_little_endian(reply->flags);
	if (flags & REPLY_QUERYFAILURE) {
		lua_pushboolean(L,0);
		lua_pushinteger(L, id);
		lua_pushlightuserdata(L, (void *)(reply+1));
		return 3;
	}

	int starting_from = to_little_endian(reply->starting);
	int number = to_little_endian(reply->number);
	int sz = (int)data_len - sizeof(*reply);
	const uint8_t * doc = (const uint8_t *)(reply+1);

	if (lua_istable(L,2)) {
		int i = 1;
		while (sz > 4) {
			lua_pushlightuserdata(L, (void *)doc);
			lua_rawseti(L, 2, i);

			int32_t doc_len = get_length((const document)doc);

			doc += doc_len;
			sz -= doc_len;

			++i;
		}
		if (i != number + 1) {
			lua_pushboolean(L,0);
			lua_pushinteger(L, id);
			return 2;
		}
		int c = lua_rawlen(L, 2);
		for (;i<=c;i++) {
			lua_pushnil(L);
			lua_rawseti(L, 2, i);
		}
	}
	lua_pushboolean(L,1);
	lua_pushinteger(L, id);
	if (number == 0)
		lua_pushnil(L);
	else
		lua_pushlightuserdata(L, (void *)(reply+1));
	if (reply->cursor_id[0] == 0 && reply->cursor_id[1]==0) {
		// closed cursor
		lua_pushnil(L);
	} else {
		lua_pushlstring(L, (const char *)(reply->cursor_id), 8);
	}
	lua_pushinteger(L, starting_from);

	return 5;
}
Example #21
0
/* Build Lua table from crypto data */
static void iwinfo_L_cryptotable(lua_State *L, struct iwinfo_crypto_entry *c)
{
	int i, j;

	lua_newtable(L);

	lua_pushboolean(L, c->enabled);
	lua_setfield(L, -2, "enabled");

	lua_pushstring(L, iwinfo_crypto_desc(c));
	lua_setfield(L, -2, "description");

	lua_pushboolean(L, (c->enabled && !c->wpa_version));
	lua_setfield(L, -2, "wep");

	lua_pushinteger(L, c->wpa_version);
	lua_setfield(L, -2, "wpa");

	lua_newtable(L);
	for (i = 0, j = 1; i < 8; i++)
	{
		if (c->pair_ciphers & (1 << i))
		{
			lua_pushstring(L, IWINFO_CIPHER_NAMES[i]);
			lua_rawseti(L, -2, j++);
		}
	}
	lua_setfield(L, -2, "pair_ciphers");

	lua_newtable(L);
	for (i = 0, j = 1; i < 8; i++)
	{
		if (c->group_ciphers & (1 << i))
		{
			lua_pushstring(L, IWINFO_CIPHER_NAMES[i]);
			lua_rawseti(L, -2, j++);
		}
	}
	lua_setfield(L, -2, "group_ciphers");

	lua_newtable(L);
	for (i = 0, j = 1; i < 8; i++)
	{
		if (c->auth_suites & (1 << i))
		{
			lua_pushstring(L, IWINFO_KMGMT_NAMES[i]);
			lua_rawseti(L, -2, j++);
		}
	}
	lua_setfield(L, -2, "auth_suites");

	lua_newtable(L);
	for (i = 0, j = 1; i < 8; i++)
	{
		if (c->auth_algs & (1 << i))
		{
			lua_pushstring(L, IWINFO_AUTH_NAMES[i]);
			lua_rawseti(L, -2, j++);
		}
	}
	lua_setfield(L, -2, "auth_algs");
}
Example #22
0
void add_assoc_name_entry(lua_State*L,const  char * key, X509_NAME * name, int shortname) /* {{{ */
{
    int i, j = -1, last = -1, obj_cnt = 0;
    char *sname;
    int nid;
    X509_NAME_ENTRY * ne;
    ASN1_STRING * str = NULL;
    ASN1_OBJECT * obj;
    char* p;

    lua_newtable(L);

    p=X509_NAME_oneline(name,NULL,0);
    lua_pushstring(L, p);
    lua_rawseti(L, -2, 0);
    OPENSSL_free(p);

    for (i = 0; i < X509_NAME_entry_count(name); i++) {
        unsigned char *to_add = NULL;
        int to_add_len = -1;
        int tindex = 0;
        //int utf8 = 0;

        ne  = X509_NAME_get_entry(name, i);
        obj = X509_NAME_ENTRY_get_object(ne);
        nid = OBJ_obj2nid(obj);
        obj_cnt = 0;

        if (shortname) {
            sname = (char *) OBJ_nid2sn(nid);
        } else {
            sname = (char *) OBJ_nid2ln(nid);
        }

        lua_newtable(L);

        last = -1;
        for (;;) {
            j = X509_NAME_get_index_by_OBJ(name, obj, last);
            if (j < 0) {
                if (last != -1) break;
            } else {
                obj_cnt++;
                ne  = X509_NAME_get_entry(name, j);
                str = X509_NAME_ENTRY_get_data(ne);

                /* Some Certificate not stardand
                if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) {
                	to_add_len = ASN1_STRING_to_UTF8(&to_add, str);
                }
                */

                to_add = ASN1_STRING_data(str);
                to_add_len = ASN1_STRING_length(str);
                tindex++;
                lua_pushlstring(L,(char *)to_add, to_add_len);
                lua_rawseti(L,-2,tindex);
            }
            last = j;
        }
        i = last;

        if (obj_cnt > 1) {
            lua_setfield(L,-2,sname);
        } else {
            lua_pop(L,1);
            if (obj_cnt && str && to_add_len > -1) {
                lua_pushlstring(L,(char *)to_add, to_add_len);
                lua_setfield(L,-2, sname);
            }
        }
    }

    if (key != NULL) {
        lua_setfield(L,-2,key);
    }
}
Example #23
0
File: main.c Project: malind/bam
/* *** */
int register_lua_globals(struct lua_State *lua, const char* script_directory, const char* filename)
{
	int i, error = 0, idx = 1;
		
	/* add standard libs */
	luaL_openlibs(lua);
	
	/* add specific functions */
	lua_register(lua, L_FUNCTION_PREFIX"add_job", lf_add_job);
	lua_register(lua, L_FUNCTION_PREFIX"add_output", lf_add_output);
	lua_register(lua, L_FUNCTION_PREFIX"add_clean", lf_add_clean);
	lua_register(lua, L_FUNCTION_PREFIX"add_pseudo", lf_add_pseudo);
	lua_register(lua, L_FUNCTION_PREFIX"add_dependency", lf_add_dependency);
	lua_register(lua, L_FUNCTION_PREFIX"add_constraint_shared", lf_add_constraint_shared);
	lua_register(lua, L_FUNCTION_PREFIX"add_constraint_exclusive", lf_add_constraint_exclusive);
	lua_register(lua, L_FUNCTION_PREFIX"default_target", lf_default_target);
	lua_register(lua, L_FUNCTION_PREFIX"set_filter", lf_set_filter);

	lua_register(lua, L_FUNCTION_PREFIX"set_priority", lf_set_priority);
	lua_register(lua, L_FUNCTION_PREFIX"modify_priority", lf_modify_priority);

	/* advanced dependency checkers */
	lua_register(lua, L_FUNCTION_PREFIX"add_dependency_cpp_set_paths", lf_add_dependency_cpp_set_paths);
	lua_register(lua, L_FUNCTION_PREFIX"add_dependency_cpp", lf_add_dependency_cpp);
	lua_register(lua, L_FUNCTION_PREFIX"add_dependency_search", lf_add_dependency_search);

	/* path manipulation */
	lua_register(lua, L_FUNCTION_PREFIX"path_join", lf_path_join);
	lua_register(lua, L_FUNCTION_PREFIX"path_normalize", lf_path_normalize);
	lua_register(lua, L_FUNCTION_PREFIX"path_isnice", lf_path_isnice);
	
	lua_register(lua, L_FUNCTION_PREFIX"path_ext", lf_path_ext);
	lua_register(lua, L_FUNCTION_PREFIX"path_dir", lf_path_dir);
	lua_register(lua, L_FUNCTION_PREFIX"path_base", lf_path_base);
	lua_register(lua, L_FUNCTION_PREFIX"path_filename", lf_path_filename);

	/* various support functions */
	lua_register(lua, L_FUNCTION_PREFIX"collect", lf_collect);
	lua_register(lua, L_FUNCTION_PREFIX"collectrecursive", lf_collectrecursive);
	lua_register(lua, L_FUNCTION_PREFIX"collectdirs", lf_collectdirs);
	lua_register(lua, L_FUNCTION_PREFIX"collectdirsrecursive", lf_collectdirsrecursive);
	
	lua_register(lua, L_FUNCTION_PREFIX"listdir", lf_listdir);
	lua_register(lua, L_FUNCTION_PREFIX"update_globalstamp", lf_update_globalstamp);
	lua_register(lua, L_FUNCTION_PREFIX"loadfile", lf_loadfile);
	
	lua_register(lua, L_FUNCTION_PREFIX"mkdir", lf_mkdir);
	lua_register(lua, L_FUNCTION_PREFIX"mkdirs", lf_mkdirs);
	lua_register(lua, L_FUNCTION_PREFIX"fileexist", lf_fileexist);
	lua_register(lua, L_FUNCTION_PREFIX"nodeexist", lf_nodeexist);
	lua_register(lua, L_FUNCTION_PREFIX"hash", lf_hash);

	lua_register(lua, L_FUNCTION_PREFIX"isstring", lf_isstring);
	lua_register(lua, L_FUNCTION_PREFIX"istable", lf_istable);
	lua_register(lua, L_FUNCTION_PREFIX"isoutput", lf_isoutput);

	lua_register(lua, L_FUNCTION_PREFIX"table_walk", lf_table_walk);
	lua_register(lua, L_FUNCTION_PREFIX"table_deepcopy", lf_table_deepcopy);
	lua_register(lua, L_FUNCTION_PREFIX"table_tostring", lf_table_tostring);
	lua_register(lua, L_FUNCTION_PREFIX"table_flatten", lf_table_flatten);

	/* error handling */
	lua_register(lua, "errorfunc", lf_errorfunc);

	/* create arguments table */
	lua_pushstring(lua, CONTEXT_LUA_SCRIPTARGS_TABLE);
	lua_newtable(lua);
	for(i = 0; i < option_num_scriptargs; i++)
	{
		const char *separator = option_scriptargs[i];
		while(*separator != '=' && *separator != '\0')
			separator++;
		if(*separator == '\0')
		{
			lua_pushnumber(lua, idx++);
			lua_pushstring(lua, option_scriptargs[i]);
		}
		else
		{
			lua_pushlstring(lua, option_scriptargs[i], separator-option_scriptargs[i]);
			lua_pushstring(lua, separator+1);
		}
		lua_settable(lua, -3);
	}
	lua_settable(lua, LUA_GLOBALSINDEX);

	/* create targets table */
	lua_pushstring(lua, CONTEXT_LUA_TARGETS_TABLE);
	lua_newtable(lua);
	for(i = 0; i < option_num_targets; i++)
	{
		lua_pushstring(lua, option_targets[i]);
		lua_rawseti(lua, -2, i);
	}
	lua_settable(lua, LUA_GLOBALSINDEX);
	
	/* set paths */
	{
		char cwd[MAX_PATH_LENGTH];
		if(!getcwd(cwd, sizeof(cwd)))
		{
			printf("%s: error: couldn't get current working directory\n", session.name);
			return -1;
		}
		
		lua_setglobalstring(lua, CONTEXT_LUA_PATH, script_directory);
		lua_setglobalstring(lua, CONTEXT_LUA_WORKPATH, cwd);
	}

	/* set version, family, platform, arch, verbocity */
	lua_setglobalstring(lua, "_bam_version", BAM_VERSION_STRING);
	lua_setglobalstring(lua, "_bam_version_complete", BAM_VERSION_STRING_COMPLETE);
	lua_setglobalstring(lua, "family", BAM_FAMILY_STRING);
	lua_setglobalstring(lua, "platform", BAM_PLATFORM_STRING);
	lua_setglobalstring(lua, "arch", BAM_ARCH_STRING);
	lua_setglobalstring(lua, "_bam_exe", session.exe);
	lua_setglobalstring(lua, "_bam_modulefilename", filename);
	lua_pushnumber(lua, session.verbose);
	lua_setglobal(lua, "verbose");

	if(option_debug_trace_vm)
		lua_sethook(lua, lua_vm_trace_hook, LUA_MASKCOUNT, 1);

	/* load base script */
	if(!option_debug_nointernal)
	{
		int ret;
		const char *p;
		int f;
		
		for(f = 0; internal_files[f].filename; f++)
		{
			p = internal_files[f].content;
			
			if(session.verbose)
				printf("%s: reading internal file '%s'\n", session.name, internal_files[f].filename);
		
			lua_getglobal(lua, "errorfunc");
			
			/* push error function to stack */
			ret = lua_load(lua, internal_base_reader, (void *)&p, internal_files[f].filename);
			if(ret != 0)
			{
				lf_errorfunc(lua);
				
				if(ret == LUA_ERRSYNTAX)
				{
				}
				else if(ret == LUA_ERRMEM)
					printf("%s: memory allocation error\n", session.name);
				else
					printf("%s: unknown error parsing base script\n", session.name);
					
				error = 1;
			}
			else if(lua_pcall(lua, 0, LUA_MULTRET, -2) != 0)
				error = 1;
		}
	}
	
	return error;
}
Example #24
0
void add_index_bool(lua_State* L, int i, int b) {
    lua_pushboolean(L,b);
    lua_rawseti(L,-2,i);
}
Example #25
0
static int lbot_openlibs_actual(lua_State *L)
{
  std::vector< std::vector<std::string> > *pvvCommandLineArguments = reinterpret_cast<std::vector< std::vector<std::string> >*>(lua_touserdata(L, 1));

  lua_createtable(L, 64, NumObjectTypes);
  for(int i = 0; lbot_enum_names[i]; )
  {
    lua_pushstring(L, lbot_enum_names[i]);
    lua_rawseti(L, -2, ++i);
  }
  for(int i = 0; i < NumObjectTypes; ++i)
  {
    lua_rawgeti(L, -1, TYPE_ENUM_NAMES + i);
    lua_pushinteger(L, static_cast<lua_Integer>(i));
    lua_rawset(L, -3);
  }
  lua_replace(L, LUA_ENVIRONINDEX);
  lua_pushvalue(L, LUA_GLOBALSINDEX);
  luaL_register(L, NULL, lbot_global_functions);
  lua_pushliteral(L, "time");
  lua_pushliteral(L, "type");
  lua_pushliteral(L, "team");
  lua_pushliteral(L, "state");
  lua_pushliteral(L, "visible");
  lua_pushliteral(L, "longitude");
  lua_pushliteral(L, "latitude");
  lua_pushcclosure(L, lbot_get_all_unit_data, 7);
  lua_setglobal(L, "GetAllUnitData");

  {
    size_t iNumCmdArgs = pvvCommandLineArguments->size();
    lua_createtable(L, static_cast<int>(iNumCmdArgs), static_cast<int>(iNumCmdArgs));
    for(size_t iArg = 0; iArg < iNumCmdArgs; ++iArg)
    {
      const std::string& sKey   = pvvCommandLineArguments->at(iArg)[0];
      const std::string& sValue = pvvCommandLineArguments->at(iArg)[1];

      lbot_pushstdstring(L, sKey);
      lbot_pushstdstring(L, sValue);
      lua_createtable(L, 2, 0);
      lua_pushvalue(L, -3);
      lua_rawseti(L, -2, 1);
      lua_pushvalue(L, -2);
      lua_rawseti(L, -2, 2);
      lua_rawseti(L, -4, static_cast<int>(iArg) + 1);
      lua_rawset(L, -3);
    }
    lua_pushcclosure(L, lbot_get_command_line_arguments, 1);
    lua_setglobal(L, "GetCommandLineArguments");
  }


  lbot_pushint(L, 0);
  lua_createtable(L, 0, 2);
  lua_pushvalue(L, LUA_GLOBALSINDEX);
  lua_setfield(L, -2, "__index");
  lua_pushcfunction(L, lbot_index__tostring);
  lua_setfield(L, -2, "__tostring");
  lua_setmetatable(L, -2);

  return 0;
}
Example #26
0
static int write_object(lua_State *L, int* indice) {
    *indice = *indice + 1;
    lua_rawseti(L, 3, *indice);
    return *indice;
}
Example #27
0
int main(int argc, char **argv)
{
#ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK
	int hack_argc = 0;	char **hack_argv = 0;
	get_utf8_arguments(hack_argc, hack_argv);
	argc = hack_argc;
	argv = hack_argv;
#endif // LOVE_LEGENDARY_UTF8_ARGV_HACK

	// Oh, you just want the version? Okay!
	if (argc > 1 && strcmp(argv[1],"--version") == 0)
	{
		printf("LOVE %s (%s)\n", love_version(), love_codename());
		return 0;
	}

	// Create the virtual machine.
	lua_State *L = lua_open();
	luaL_openlibs(L);

	love_preload(L, luaopen_love, "love");

	luaopen_love(L);

	// Add command line arguments to global arg (like stand-alone Lua).
	{
		lua_newtable(L);

		if (argc > 0)
		{
			lua_pushstring(L, argv[0]);
			lua_rawseti(L, -2, -2);
		}

		lua_pushstring(L, "embedded boot.lua");
		lua_rawseti(L, -2, -1);

		for (int i = 1; i<argc; i++)
		{
			lua_pushstring(L, argv[i]);
			lua_rawseti(L, -2, i);
		}

		lua_setglobal(L, "arg");
	}

	// Add love.__exe = true.
	// This indicates that we're running the
	// standalone version of love, and not the
	// DLL version.
	{
		lua_getglobal(L, "love");
		lua_pushboolean(L, 1);
		lua_setfield(L, -2, "_exe");
		lua_pop(L, 1);
	}

	// Boot
	luaopen_love_boot(L);
	lua_call(L, 0, 1);

	int retval = 0;
	if (lua_isnumber(L, 1))
		retval = (int) lua_tonumber(L, 1);

	lua_close(L);

#ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK
	if (hack_argv)
	{
		for (int i = 0; i<hack_argc; ++i)
			delete [] hack_argv[i];
		delete [] hack_argv;
	}
#endif // LOVE_LEGENDARY_UTF8_ARGV_HACK
	return retval;
}
Example #28
0
static void serialize_value(lua_State *L, int pos, luaL_Buffer* frame, int* indice, uint16_t* key) {
    if (!lua_checkstack(L, 2)) {
        luaL_error(L, "cannot serialize: stack won't grow");
    }
    uint8_t type = get_luatobin_type(L, pos);
    switch (type) {
    case BIN_NIL: {
        //printf("(nil[1])");
        lua_pushlstring(L, (char *) &type, 1);
        write_object(L, indice);
        break;
    }

    case BIN_BOOLEAN: {
        //printf("(boolean[2])");
        int boolean = lua_toboolean(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        luaL_addchar(frame, boolean & 0xFF);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_DOUBLE: {
        double number = lua_tonumber(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.double_) hton(&number, sizeof(number), sendian.double_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_INTEGER: {
        int32_t number = lua_tointeger(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.int32_) hton(&number, sizeof(number), sendian.int32_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_STRING: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(stringref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        size_t s;
        const char* string = lua_tolstring(L, pos, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: string length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(string[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_FUNCTION: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(functionref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        serialize_function(L, frame, pos);
        size_t s;
        const char* string = lua_tolstring(L, -1, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: function length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(function[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        lua_pop(L, 1); // remove the serialized function
        break;
    }

    case BIN_TABLE: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(tableref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        // reserved for table header (as size cannot be calculated beforehand)
        *indice = *indice + 1;
        int header = *indice;
        //printf("{table=");
        int top;
        size_t s = 0;
        lua_pushnil(L);
        while (lua_next(L, pos) != 0) {
            top = lua_gettop(L);
            serialize_value(L, top - 1, frame, indice, key);
            serialize_value(L, top, frame, indice, key);
            lua_pop(L, 1);
            s++;
        }
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: table length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        luaL_pushresult(frame);
        // set table header
        lua_rawseti(L, 3, header);
        //printf("[%d]}", size);
        break;
    }

    default:
        luaL_error(L, "cannot serialize: unsupported type (%d)", lua_type(L, pos));
    }
}
Example #29
0
static int push_reply(lua_State * L, redisReply * pReply)
{
  switch (pReply->type)
  {
    case REDIS_REPLY_STATUS:
      luaL_checkstack(L, 2, "not enough stack to push reply");

      lua_pushvalue(L, lua_upvalueindex(1)); /* M (module table) */
      lua_getfield(L, -1, "status"); /* status = M.status */
      lua_remove(L, -2); /* Remove module table from stack */

      lua_pushlstring(L, pReply->str, pReply->len); /* name */
      lua_gettable(L, -2); /* status[name] */

      lua_remove(L, -2); /* Remove status table from stack */

      break;

    case REDIS_REPLY_ERROR:
      /* Not caching errors, they are (hopefully) not that common */
      push_new_const(L, pReply->str, pReply->len, REDIS_REPLY_ERROR);
      break;

    case REDIS_REPLY_INTEGER:
      luaL_checkstack(L, 1, "not enough stack to push reply");
      lua_pushinteger(L, pReply->integer);
      break;

    case REDIS_REPLY_NIL:
      luaL_checkstack(L, 2, "not enough stack to push reply");
      lua_pushvalue(L, lua_upvalueindex(1)); /* module table */
      lua_getfield(L, -1, LUAHIREDIS_KEY_NIL);
      lua_remove(L, -2); /* module table */
      break;

    case REDIS_REPLY_STRING:
      luaL_checkstack(L, 1, "not enough stack to push reply");
      lua_pushlstring(L, pReply->str, pReply->len);
      break;

    case REDIS_REPLY_ARRAY:
    {
      unsigned int i = 0;

      luaL_checkstack(L, 2, "not enough stack to push reply");

      lua_createtable(L, pReply->elements, 0);

      for (i = 0; i < pReply->elements; ++i)
      {
        /*
        * Not controlling recursion depth:
        * if we parsed the reply somehow,
        * we hope to be able to push it.
        */

        push_reply(L, pReply->element[i]);
        lua_rawseti(L, -2, i + 1); /* Store sub-reply */
      }

      break;
    }

    default: /* should not happen */
      return luaL_error(L, "command: unknown reply type: %d", pReply->type);
  }

  /*
  * Always returning a single value.
  * If changed, change REDIS_REPLY_ARRAY above.
  */
  return 1;
}
Example #30
0
/** Set indexed value without invoking meta methods.
 * Sets t[n]=v, where t is a table at index idx and v is the value at the
 * top of the stack.
 * @param idx index of the table
 * @param n index in the table
 */
void
LuaContext::raw_seti(int idx, int n)
{
  lua_rawseti(__L, idx, n);
}