Beispiel #1
0
int luaCtx_toboolean(LuaContext_t *aCtx, int idx)
{
    return lua_toboolean(aCtx->luaState, idx);
}
Beispiel #2
0
template<> bool Eluna::CHECKVAL<bool>(lua_State* L, int narg, bool def)
{
    return lua_isnone(L, narg) ? def : lua_isnumber(L, narg) ? luaL_optnumber(L, narg, 1) ? true : false : lua_toboolean(L, narg);
}
Beispiel #3
0
int lua_echo ( lua_State *L )
{
    if ( !lua_isuserdata ( L, 1 ) ) {
        luaL_error ( L, "miss epd!" );
        return 0;
    }

    int nargs = lua_gettop ( L );

    if ( nargs < 2 ) {
        luaL_error ( L, "miss content!" );
        return 0;
    }

    size_t len = 0;
    epdata_t *epd = lua_touserdata ( L, 1 );

    if ( lua_istable ( L, 2 ) ) {
        len = lua_calc_strlen_in_table ( L, 2, 2, 0 /* strict */ );

        if ( len < 1 ) {
            return 0;
        }

        char *buf = tbuf_4096;

        if ( len > 4096 ) {
            buf = large_malloc ( len );

            if ( !buf ) {
                return 0;
            }

            lua_copy_str_in_table ( L, 2, buf );
            network_send ( epd, buf, len );
            free ( buf );

        } else {
            lua_copy_str_in_table ( L, 2, buf );
            network_send ( epd, buf, len );
        }

    } else {
        const char *data = NULL;
        int i = 0;

        for ( i = 2; i <= nargs; i++ ) {
            if ( lua_isboolean ( L, i ) ) {
                if ( lua_toboolean ( L, i ) ) {
                    network_send ( epd, "true", 4 );

                } else {
                    network_send ( epd, "false", 5 );
                }

            } else {
                data = lua_tolstring ( L, i, &len );
                network_send ( epd, data, len );
            }
        }
    }

    return 0;
}
Beispiel #4
0
static int function(lua_State *L)
{
	gnative_Class *cls = (gnative_Class*)lua_touserdata(L, lua_upvalueindex(1));
	const char *name = lua_tostring(L, lua_upvalueindex(2));

	gnative_Function **functions = gnative_ClassGetFunctionsByName(cls, name);
	
	gnative_Function *function = match(L, functions);

	int parameterCount = lua_gettop(L);

	gnative_Type *parameterTypes = gnative_FunctionGetParameterTypes(function);

	gnative_Object *self;
	int delta;
	if (gnative_FunctionIsStatic(function))
	{
		self = NULL;
		delta = 0;
	}
	else
	{
		self = toObject(L, 1);
		delta = 1;
	}

	std::vector<gnative_Value> parameters;
	
	for (int i = delta; i < parameterCount; ++i)
	{
		gnative_Type t = parameterTypes[i - delta];
		gnative_Value v;
		switch (lua_type(L, i + 1))
		{
		case LUA_TBOOLEAN:
			v = booleanToValue(lua_toboolean(L, i + 1), t);
			break;
		case LUA_TLIGHTUSERDATA:
			break;
		case LUA_TNUMBER:
			v = numberToValue(lua_tonumber(L, i + 1), t);
			break;
		case LUA_TSTRING:
			v = stringToValue(lua_tostring(L, i + 1), t);
			break;
		case LUA_TTABLE:
			v.obj = toObject(L, i + 1);
			break;
		case LUA_TNIL:
			v.obj = NULL;
			break;
		}
		parameters.push_back(v);
	}
	
	gnative_Value v = gnative_FunctionCall(function, self, parameters.empty() ? NULL : &parameters[0]);

	gnative_Type t = gnative_FunctionGetReturnType(function);
	
	return pushValue(L, v, t, true);
}
Beispiel #5
0
static int stack_pop (lua_State *L) {
  return pop(L, checkstack(L, 1), lua_toboolean(L, 2));
}
static int
ngx_stream_lua_ngx_echo(lua_State *L, unsigned newline)
{
    ngx_stream_session_t        *s;
    ngx_stream_lua_ctx_t        *ctx;
    const char                  *p;
    size_t                       len;
    size_t                       size;
    ngx_buf_t                   *b;
    ngx_chain_t                 *cl;
    ngx_int_t                    rc;
    int                          i;
    int                          nargs;
    int                          type;
    ngx_err_t                    err;
    const char                  *msg;
    u_char                       errbuf[NGX_STREAM_LUA_MAX_ERROR_STR];

    s = ngx_stream_lua_get_session(L);
    if (s == NULL) {
        return luaL_error(L, "no session object found");
    }

    ctx = ngx_stream_get_module_ctx(s, ngx_stream_lua_module);

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

    ngx_stream_lua_check_context(L, ctx, NGX_STREAM_LUA_CONTEXT_CONTENT);

#if 0
    if (ctx->acquired_raw_req_socket) {
        lua_pushnil(L);
        lua_pushliteral(L, "raw session socket acquired");
        return 2;
    }
#endif

    if (ctx->eof) {
        lua_pushnil(L);
        lua_pushliteral(L, "seen eof");
        return 2;
    }

    nargs = lua_gettop(L);
    size = 0;

    for (i = 1; i <= nargs; i++) {

        type = lua_type(L, i);

        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:

                lua_tolstring(L, i, &len);
                size += len;
                break;

            case LUA_TNIL:

                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:

                if (lua_toboolean(L, i)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TTABLE:

                size += ngx_stream_lua_calc_strlen_in_table(L, i, i,
                                                            0 /* strict */);
                break;

            case LUA_TLIGHTUSERDATA:

                dd("userdata: %p", lua_touserdata(L, i));

                if (lua_touserdata(L, i) == NULL) {
                    size += sizeof("null") - 1;
                    break;
                }

                continue;

            default:

                msg = lua_pushfstring(L, "string, number, boolean, nil, "
                                      "ngx.null, or array table expected, "
                                      "but got %s", lua_typename(L, type));

                return luaL_argerror(L, i, msg);
        }
    }

    if (newline) {
        size += sizeof("\n") - 1;
    }

    if (size == 0) {
        /* do nothing for empty strings */
        lua_pushinteger(L, 1);
        return 1;
    }

    cl = ngx_stream_lua_chain_get_free_buf(s->connection->log,
                                           s->connection->pool,
                                           &ctx->free_bufs, size);

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

    b = cl->buf;

    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                p = lua_tolstring(L, i, &len);
                b->last = ngx_copy(b->last, (u_char *) p, len);
                break;

            case LUA_TNIL:
                *b->last++ = 'n';
                *b->last++ = 'i';
                *b->last++ = 'l';
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    *b->last++ = 't';
                    *b->last++ = 'r';
                    *b->last++ = 'u';
                    *b->last++ = 'e';

                } else {
                    *b->last++ = 'f';
                    *b->last++ = 'a';
                    *b->last++ = 'l';
                    *b->last++ = 's';
                    *b->last++ = 'e';
                }

                break;

            case LUA_TTABLE:
                b->last = ngx_stream_lua_copy_str_in_table(L, i, b->last);
                break;

            case LUA_TLIGHTUSERDATA:
                *b->last++ = 'n';
                *b->last++ = 'u';
                *b->last++ = 'l';
                *b->last++ = 'l';
                break;

            default:
                return luaL_error(L, "impossible to reach here");
        }
    }

    if (newline) {
        *b->last++ = '\n';
    }

#if 0
    if (b->last != b->end) {
        return luaL_error(L, "buffer error: %p != %p", b->last, b->end);
    }
#endif

    ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0,
                   newline ? "stream lua say response"
                           : "stream lua print response");

    ngx_set_errno(0);

    rc = ngx_stream_lua_send_chain_link(s, ctx, cl);

    if (rc == NGX_ERROR) {
        err = ngx_errno;

        lua_pushnil(L);

        if (err) {
            size = ngx_strerror(err, errbuf, sizeof(errbuf)) - errbuf;
            ngx_strlow(errbuf, errbuf, size);
            lua_pushlstring(L, (char *) errbuf, size);

        } else {
            lua_pushliteral(L, "unknown");
        }

        return 2;
    }

    dd("downstream write: %d, buf len: %d", (int) rc,
       (int) (b->last - b->pos));

    lua_pushinteger(L, 1);
    return 1;
}
Beispiel #7
0
void read_object_properties(lua_State *L, int index,
		ObjectProperties *prop)
{
	if(index < 0)
		index = lua_gettop(L) + 1 + index;
	if(!lua_istable(L, index))
		return;

	prop->hp_max = getintfield_default(L, -1, "hp_max", 10);

	getboolfield(L, -1, "physical", prop->physical);
	getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);

	getfloatfield(L, -1, "weight", prop->weight);

	lua_getfield(L, -1, "collisionbox");
	if(lua_istable(L, -1))
		prop->collisionbox = read_aabb3f(L, -1, 1.0);
	lua_pop(L, 1);

	getstringfield(L, -1, "visual", prop->visual);

	getstringfield(L, -1, "mesh", prop->mesh);

	lua_getfield(L, -1, "visual_size");
	if(lua_istable(L, -1))
		prop->visual_size = read_v2f(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "textures");
	if(lua_istable(L, -1)){
		prop->textures.clear();
		int table = lua_gettop(L);
		lua_pushnil(L);
		while(lua_next(L, table) != 0){
			// key at index -2 and value at index -1
			if(lua_isstring(L, -1))
				prop->textures.push_back(lua_tostring(L, -1));
			else
				prop->textures.push_back("");
			// removes value, keeps key for next iteration
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "colors");
	if(lua_istable(L, -1)){
		prop->colors.clear();
		int table = lua_gettop(L);
		lua_pushnil(L);
		while(lua_next(L, table) != 0){
			// key at index -2 and value at index -1
			if(lua_isstring(L, -1))
				prop->colors.push_back(readARGB8(L, -1));
			else
				prop->colors.push_back(video::SColor(255, 255, 255, 255));
			// removes value, keeps key for next iteration
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "spritediv");
	if(lua_istable(L, -1))
		prop->spritediv = read_v2s16(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "initial_sprite_basepos");
	if(lua_istable(L, -1))
		prop->initial_sprite_basepos = read_v2s16(L, -1);
	lua_pop(L, 1);

	getboolfield(L, -1, "is_visible", prop->is_visible);
	getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
	getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
	if (getfloatfield(L, -1, "stepheight", prop->stepheight))
		prop->stepheight *= BS;
	lua_getfield(L, -1, "automatic_face_movement_dir");
	if (lua_isnumber(L, -1)) {
		prop->automatic_face_movement_dir = true;
		prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
	} else if (lua_isboolean(L, -1)) {
		prop->automatic_face_movement_dir = lua_toboolean(L, -1);
		prop->automatic_face_movement_dir_offset = 0.0;
	}
	lua_pop(L, 1);
}
Beispiel #8
0
bool luaM_toboolean(lua_State *L, int idx)
{
	if (lua_type(L, idx) == LUA_TNUMBER)
		return lua_tonumber(L, idx) != 0;
	return lua_toboolean(L, idx) > 0;
}
Beispiel #9
0
/*****************************************************************************
 * Called through lua_scripts_batch_execute to call 'probe' on
 * the script pointed by psz_filename.
 *****************************************************************************/
static int probe_luascript( vlc_object_t *p_this, const char * psz_filename,
                            void * user_data )
{
    VLC_UNUSED(user_data);
    demux_t * p_demux = (demux_t *)p_this;

    p_demux->p_sys->psz_filename = strdup(psz_filename);

    /* Initialise Lua state structure */
    lua_State *L = luaL_newstate();
    if( !L )
    {
        msg_Err( p_demux, "Could not create new Lua State" );
        goto error;
    }
    p_demux->p_sys->L = L;

    /* Load Lua libraries */
    luaL_openlibs( L ); /* FIXME: Don't open all the libs? */

    vlclua_set_this( L, p_demux );
    luaL_register( L, "vlc", p_reg );
    luaopen_msg( L );
    luaopen_strings( L );
    luaopen_stream( L );
    luaopen_variables( L );
    luaopen_xml( L );
    lua_pushstring( L, p_demux->psz_location );
    lua_setfield( L, -2, "path" );
    lua_pushstring( L, p_demux->psz_access );
    lua_setfield( L, -2, "access" );

    lua_pop( L, 1 );

    /* Setup the module search path */
    if( vlclua_add_modules_path( p_demux, L, psz_filename ) )
    {
        msg_Warn( p_demux, "Error while setting the module search path for %s",
                  psz_filename );
        goto error;
    }

    /* Load and run the script(s) */
    if( luaL_dofile( L, psz_filename ) )
    {
        msg_Warn( p_demux, "Error loading script %s: %s", psz_filename,
                  lua_tostring( L, lua_gettop( L ) ) );
        goto error;
    }

    lua_getglobal( L, "probe" );

    if( !lua_isfunction( L, -1 ) )
    {
        msg_Warn( p_demux, "Error while running script %s, "
                  "function probe() not found", psz_filename );
        goto error;
    }

    if( lua_pcall( L, 0, 1, 0 ) )
    {
        msg_Warn( p_demux, "Error while running script %s, "
                  "function probe(): %s", psz_filename,
                  lua_tostring( L, lua_gettop( L ) ) );
        goto error;
    }

    if( lua_gettop( L ) )
    {
        if( lua_toboolean( L, 1 ) )
        {
            msg_Dbg( p_demux, "Lua playlist script %s's "
                     "probe() function was successful", psz_filename );
            lua_pop( L, 1 );
            return VLC_SUCCESS;
        }
    }

error:
    lua_pop( L, 1 );
    lua_close( p_demux->p_sys->L );
    p_demux->p_sys->L = NULL;
    FREENULL( p_demux->p_sys->psz_filename );
    return VLC_EGENERIC;
}
Beispiel #10
0
static int
ngx_http_lua_ngx_req_set_body_file(lua_State *L)
{
    u_char                      *p;
    ngx_http_request_t          *r;
    int                          n;
    ngx_http_request_body_t     *rb;
    ngx_temp_file_t             *tf;
    ngx_buf_t                   *b;
    ngx_str_t                    name;
    ngx_int_t                    rc;
    int                          clean;
    ngx_open_file_info_t         of;
    ngx_str_t                    key, value;
    ngx_pool_cleanup_t          *cln;
    ngx_pool_cleanup_file_t     *clnf;
    ngx_err_t                    err;
    ngx_chain_t                 *cl;
    ngx_buf_tag_t                tag;

    n = lua_gettop(L);

    if (n != 1 && n != 2) {
        return luaL_error(L, "expecting 1 or 2 arguments but seen %d", n);
    }

    p = (u_char *) luaL_checklstring(L, 1, &name.len);

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

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

    if (r->discard_body) {
        return luaL_error(L, "request body already discarded asynchronously");
    }

    if (r->request_body == NULL) {
        return luaL_error(L, "request body not read yet");
    }

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

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

    if (n == 2) {
        luaL_checktype(L, 2, LUA_TBOOLEAN);
        clean = lua_toboolean(L, 2);

    } else {
        clean = 0;
    }

    dd("clean: %d", (int) clean);

    rb = r->request_body;

    /* clean up existing r->request_body->bufs (if any) */

    tag = (ngx_buf_tag_t) &ngx_http_lua_module;

    if (rb->bufs) {
        dd("XXX reusing buf");

        for (cl = rb->bufs; cl; cl = cl->next) {
            if (cl->buf->tag == tag && cl->buf->temporary) {
                dd("free old request body buffer: size:%d",
                   (int) ngx_buf_size(cl->buf));

                ngx_pfree(r->pool, cl->buf->start);
                cl->buf->tag = (ngx_buf_tag_t) NULL;
                cl->buf->temporary = 0;
            }
        }

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

        ngx_memzero(b, sizeof(ngx_buf_t));

        b->tag = tag;

    } else {

        dd("XXX creating new buf");

        rb->bufs = ngx_alloc_chain_link(r->pool);
        if (rb->bufs == NULL) {
            return luaL_error(L, "out of memory");
        }
        rb->bufs->next = NULL;

        b = ngx_calloc_buf(r->pool);
        if (b == NULL) {
            return luaL_error(L, "out of memory");
        }

        b->tag = tag;

        rb->bufs->buf = b;
        rb->buf = b;
    }

    b->last_in_chain = 1;

    /* just make r->request_body->temp_file a bare stub */

    tf = rb->temp_file;

    if (tf) {
        if (tf->file.fd != NGX_INVALID_FILE) {

            dd("cleaning temp file %.*s", (int) tf->file.name.len,
               tf->file.name.data);

            ngx_http_lua_pool_cleanup_file(r->pool, tf->file.fd);

            ngx_memzero(tf, sizeof(ngx_temp_file_t));

            tf->file.fd = NGX_INVALID_FILE;

            dd("temp file cleaned: %.*s", (int) tf->file.name.len,
               tf->file.name.data);
        }

    } else {

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

        tf->file.fd = NGX_INVALID_FILE;
        rb->temp_file = tf;
    }

    /* read the file info and construct an in-file buf */

    ngx_memzero(&of, sizeof(ngx_open_file_info_t));

    if (ngx_http_lua_open_and_stat_file(name.data, &of, r->connection->log)
        != NGX_OK)
    {
        return luaL_error(L, "%s \"%s\" failed", of.failed, name.data);
    }

    dd("XXX new body file fd: %d", of.fd);

    tf->file.fd = of.fd;
    tf->file.name = name;
    tf->file.log = r->connection->log;

    /* FIXME we should not always set directio here */
    tf->file.directio = 1;

    if (of.size == 0) {
        if (clean) {
            if (ngx_delete_file(name.data) == NGX_FILE_ERROR) {
                err = ngx_errno;

                if (err != NGX_ENOENT) {
                    ngx_log_error(NGX_LOG_CRIT, r->connection->log, err,
                                  ngx_delete_file_n " \"%s\" failed",
                                  name.data);
                }
            }
        }

        if (ngx_close_file(of.fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_ALERT, r->connection->log, ngx_errno,
                          ngx_close_file_n " \"%s\" failed", name.data);
        }

        r->request_body->bufs = NULL;
        r->request_body->buf = NULL;

        goto set_header;
    }

    /* register file cleanup hook */

    cln = ngx_pool_cleanup_add(r->pool,
                               sizeof(ngx_pool_cleanup_file_t));

    if (cln == NULL) {
        return luaL_error(L, "out of memory");
    }

    cln->handler = clean ? ngx_pool_delete_file : ngx_pool_cleanup_file;
    clnf = cln->data;

    clnf->fd = of.fd;
    clnf->name = name.data;
    clnf->log = r->pool->log;

    b->file = &tf->file;
    if (b->file == NULL) {
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    dd("XXX file size: %d", (int) of.size);

    b->file_pos = 0;
    b->file_last = of.size;

    b->in_file = 1;

    dd("buf file: %p, f:%u", b->file, b->in_file);

set_header:
    /* override input header Content-Length (value must be null terminated) */

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

    value.len = ngx_sprintf(value.data, "%O", of.size) - value.data;
    value.data[value.len] = '\0';

    r->headers_in.content_length_n = of.size;

    if (r->headers_in.content_length) {
        r->headers_in.content_length->value.data = value.data;
        r->headers_in.content_length->value.len = value.len;

    } else {

        ngx_str_set(&key, "Content-Length");

        rc = ngx_http_lua_set_input_header(r, key, value, 1 /* override */);
        if (rc != NGX_OK) {
            return luaL_error(L, "failed to reset the Content-Length "
                              "input header");
        }
    }

    return 0;
}
Beispiel #11
0
	void WriteGeometry(lua_State* L, Buffer& data_buf, Buffer& name_buf, uint32& mat_count, uint32& vert_count, uint32& tri_count)
	{
		FoundNamesMap found_names;

		lua_getfield(L, 1, "materials");
		uint32 count = lua_objlen(L, -1);
		mat_count = count;
		for (uint32 i = 1; i <= count; ++i)
		{
			lua_pushinteger(L, i);
			lua_gettable(L, -2);

			Material mat;
			mat.index = i - 1;
			
			mat.name_index = AddName(L, "name", name_buf, found_names);
			mat.shader_index = AddName(L, "shader", name_buf, found_names);

			mat.property_count = lua_objlen(L, -1);
			data_buf.Add(&mat, Material::SIZE);

			for (uint32 j = 1; j <= mat.property_count; ++j)
			{
				lua_pushinteger(L, j);
				lua_gettable(L, -2);

				Property prop;
				prop.name_index = AddName(L, "name", name_buf, found_names);
				prop.type = GetInt(L, -1, "type");
				if (prop.type == 0)
				{
					prop.value.f = GetFloat(L, -1, "value");
				}
				else if (prop.type == 3)
				{
					lua_getfield(L, -1, "value");
					double val = lua_tonumber(L, -1);
					lua_pop(L, 1);
					prop.value.i = static_cast<uint32>(val);
				}
				else
				{
					prop.value.i = AddName(L, "value", name_buf, found_names);
				}

				data_buf.Add(&prop, Property::SIZE);
				lua_pop(L, 1);
			}

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

		lua_getfield(L, 1, "vertices");
		lua_getfield(L, -1, "binary");
		int binary = lua_toboolean(L, -1);
		lua_pop(L, 1);

		if (binary)
		{
			lua_getfield(L, -1, "count");
			int count = lua_tointeger(L, -1);
			lua_getfield(L, -2, "data");
			void* data = lua_touserdata(L, -1);
			uint32 len = lua_objlen(L, -1);
			lua_pop(L, 2);

			data_buf.Add(data, len);
			vert_count = count;
		}
		else
		{
			count = lua_objlen(L, -1);
			vert_count = count;
			for (uint32 i = 1; i <= count; ++i)
			{
				lua_pushinteger(L, i);
				lua_gettable(L, -2);

				Vertex vert;
				vert.x = GetFloat(L, -1, "x");
				vert.y = GetFloat(L, -1, "y");
				vert.z = GetFloat(L, -1, "z");
				vert.i = GetFloat(L, -1, "i");
				vert.j = GetFloat(L, -1, "j");
				vert.k = GetFloat(L, -1, "k");
				vert.u = GetFloat(L, -1, "u");
				vert.v = GetFloat(L, -1, "v");

				data_buf.Add(&vert, Vertex::SIZE);
				lua_pop(L, 1);
			}
		}
		lua_pop(L, 1);

		lua_getfield(L, 1, "triangles");
		lua_getfield(L, -1, "binary");
		binary = lua_toboolean(L, -1);
		lua_pop(L, 1);

		if (binary)
		{
			lua_getfield(L, -1, "count");
			int count = lua_tointeger(L, -1);
			lua_getfield(L, -2, "data");
			void* data = lua_touserdata(L, -1);
			uint32 len = lua_objlen(L, -1);
			lua_pop(L, 2);

			data_buf.Add(data, len);
			tri_count = count;
		}
		else
		{
			count = lua_objlen(L, -1);
			tri_count = count;
			for (uint32 i = 1; i <= count; ++i)
			{
				lua_pushinteger(L, i);
				lua_gettable(L, -2);

				Triangle tri;
				for (int j = 0; j < 3; ++j)
				{
					lua_pushinteger(L, j + 1);
					lua_gettable(L, -2);
					tri.index[j] = lua_tointeger(L, -1);
					lua_pop(L, 1);
				}
				lua_getfield(L, -1, "material");
				tri.material = lua_tointeger(L, -1);
				lua_pop(L, 1);
				tri.flag = GetInt(L, -1, "flag");

				data_buf.Add(&tri, Triangle::SIZE);
				lua_pop(L, 1);
			}
		}
		lua_pop(L, 1);
	}
Beispiel #12
0
	template<> bool FromStack<bool>( Lua *L, bool &Object, int iOffset ) { Object = !!lua_toboolean( L, iOffset ); return true; }
Beispiel #13
0
lua_Integer checkboolean (lua_State *L, int narg) {
	lua_Integer d = lua_toboolean(L, narg);
	if (d == 0 && !lua_isboolean(L, narg))  /* avoid extra test when d is not 0 */
		luaL_typerror(L, narg, lua_typename(L, LUA_TBOOLEAN));
	return d;
}
Beispiel #14
0
static void tableDump(lua_State *L, int index)
{
    int top = lua_gettop(L);
    lua_pushvalue(L, index);
    int t = top + 1;

    if (lua_type(L, t) != LUA_TTABLE) {
        printf("not a table\n");
        return;
    }

    lua_pushnil(L);
    while (lua_next(L, t) != 0) {
        /* key */
        {
            int type = lua_type(L, -2);
            switch (type) {
            case LUA_TSTRING: /* strings */
                printf("`%s'", lua_tostring(L, -2));
                break;

            case LUA_TBOOLEAN: /* booleans */
                printf(lua_toboolean(L, -2) ? "true" : "false");
                break;

            case LUA_TNUMBER: /* numbers */
                printf("%g", lua_tonumber(L, -2));
                break;

            default: /* other values */
                printf("%s", lua_typename(L, type));
                break;
            }
            printf(":  "); /* put a separator */
        }

        /* value */
        {
            int type = lua_type(L, -1);
            switch (type) {
            case LUA_TSTRING: /* strings */
                printf("`%s'", lua_tostring(L, -1));
                break;

            case LUA_TBOOLEAN: /* booleans */
                printf(lua_toboolean(L, -1) ? "true" : "false");
                break;

            case LUA_TNUMBER: /* numbers */
                printf("%g", lua_tonumber(L, -1));
                break;

            default: /* other values */
                printf("%s", lua_typename(L, type));
                break;
            }
            printf(",  "); /* put a separator */
        }

        lua_pop(L, 1); /* pop value, keep key */
    }
    printf("\n");

    lua_settop(L, top);
}
size_t
ngx_stream_lua_calc_strlen_in_table(lua_State *L, int index, int arg_i,
    unsigned strict)
{
    double              key;
    int                 max;
    int                 i;
    int                 type;
    size_t              size;
    size_t              len;
    const char         *msg;

    if (index < 0) {
        index = lua_gettop(L) + index + 1;
    }

    dd("table index: %d", index);

    max = 0;

    lua_pushnil(L); /* stack: table key */
    while (lua_next(L, index) != 0) { /* stack: table key value */
        dd("key type: %s", luaL_typename(L, -2));

        if (lua_type(L, -2) == LUA_TNUMBER) {

            key = lua_tonumber(L, -2);

            dd("key value: %d", (int) key);

            if (floor(key) == key && key >= 1) {
                if (key > max) {
                    max = (int) key;
                }

                lua_pop(L, 1); /* stack: table key */
                continue;
            }
        }

        /* not an array (non positive integer key) */
        lua_pop(L, 2); /* stack: table */

        luaL_argerror(L, arg_i, "non-array table found");
        return 0;
    }

    size = 0;

    for (i = 1; i <= max; i++) {
        lua_rawgeti(L, index, i); /* stack: table value */
        type = lua_type(L, -1);

        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:

                lua_tolstring(L, -1, &len);
                size += len;
                break;

            case LUA_TNIL:

                if (strict) {
                    goto bad_type;
                }

                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:

                if (strict) {
                    goto bad_type;
                }

                if (lua_toboolean(L, -1)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TTABLE:

                size += ngx_stream_lua_calc_strlen_in_table(L, -1, arg_i,
                                                            strict);
                break;

            case LUA_TLIGHTUSERDATA:

                if (strict) {
                    goto bad_type;
                }

                if (lua_touserdata(L, -1) == NULL) {
                    size += sizeof("null") - 1;
                    break;
                }

                continue;

            default:

bad_type:

                msg = lua_pushfstring(L, "bad data type %s found",
                                      lua_typename(L, type));
                return luaL_argerror(L, arg_i, msg);
        }

        lua_pop(L, 1); /* stack: table */
    }

    return size;
}
Beispiel #16
0
static int resource_set_add_resource(lua_State *L)
{
    int narg;
    resource_set_lua_t *rset;
    resource_lua_t *resource;
    const char *resource_name;
    bool shared = FALSE;
    bool mandatory = TRUE;
    mrp_attr_t attribute_list[MAX_ATTRS], *attrs;

    mrp_debug("> add_resource");

    narg = lua_gettop(L);

    if (narg != 2)
        return luaL_error(L, "expecting one argument");

    rset = resource_set_lua_check(L, 1);

    if (!rset)
        goto error;

    /* the argument should be a table with at least "resource_name" index */

    if (!lua_istable(L, -1))
        return luaL_error(L, "argument error -- not a table");

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

    if (!lua_isstring(L, -1))
        return luaL_error(L, "'resource_name' is a mandatory field");

    resource_name = lua_tostring(L, -1);
    lua_pop(L, 1);

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

    if (lua_isboolean(L, -1)) {
        mandatory = lua_toboolean(L, -1);
    }
    lua_pop(L, 1);

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

    if (lua_isboolean(L, -1)) {
        shared = lua_toboolean(L, -1);
    }
    lua_pop(L, 1);

    /* create resource object and add it to the resource table in the resource
     * set object */

    resource = (resource_lua_t *) mrp_lua_create_object(L, RESOURCE_LUA_CLASS,
            NULL, 0);

    if (!resource)
        goto error;

    /* mrp_lua_object_ref_value(resource, L, 0); */

    resource->mandatory = mandatory;
    resource->shared = shared;
    resource->acquired = FALSE;
    resource->available = FALSE;
    resource->resource_name = mrp_strdup(resource_name);

    if (!resource->resource_name)
        goto error;

    resource->parent = rset;
    resource->L = L;

    resource->real_attributes = (attribute_lua_t *) mrp_lua_create_object(L,
            ATTRIBUTE_LUA_CLASS, NULL, 0);

    if (!resource->real_attributes)
        goto error;

    /* mrp_lua_object_ref_value(resource->real_attributes, L, 0); */

    resource->real_attributes->L = L;
    resource->real_attributes->parent = resource;
    resource->real_attributes->resource_set = rset;
    resource->real_attributes->initialized = TRUE;

    attrs = mrp_resource_set_read_all_attributes(rset->resource_set,
            resource->resource_name, MAX_ATTRS-1, attribute_list);

    if (mrp_resource_set_add_resource(rset->resource_set,
            resource->resource_name, shared, attrs, mandatory) < 0)
        goto error;

    /* add to resource map */

    mrp_debug("inserted resource %s to %p", resource->resource_name, rset);
    mrp_htbl_insert(rset->resources, resource->resource_name, resource);

    return 0;

error:
    /* TODO: clean up the already allocated objects */

    return luaL_error(L, "internal resource library error");
}
u_char *
ngx_stream_lua_copy_str_in_table(lua_State *L, int index, u_char *dst)
{
    double               key;
    int                  max;
    int                  i;
    int                  type;
    size_t               len;
    u_char              *p;

    if (index < 0) {
        index = lua_gettop(L) + index + 1;
    }

    max = 0;

    lua_pushnil(L); /* stack: table key */
    while (lua_next(L, index) != 0) { /* stack: table key value */
        key = lua_tonumber(L, -2);
        if (key > max) {
            max = (int) key;
        }

        lua_pop(L, 1); /* stack: table key */
    }

    for (i = 1; i <= max; i++) {
        lua_rawgeti(L, index, i); /* stack: table value */
        type = lua_type(L, -1);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                p = (u_char *) lua_tolstring(L, -1, &len);
                dst = ngx_copy(dst, p, len);
                break;

            case LUA_TNIL:
                *dst++ = 'n';
                *dst++ = 'i';
                *dst++ = 'l';
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, -1)) {
                    *dst++ = 't';
                    *dst++ = 'r';
                    *dst++ = 'u';
                    *dst++ = 'e';

                } else {
                    *dst++ = 'f';
                    *dst++ = 'a';
                    *dst++ = 'l';
                    *dst++ = 's';
                    *dst++ = 'e';
                }

                break;

            case LUA_TTABLE:
                dst = ngx_stream_lua_copy_str_in_table(L, -1, dst);
                break;

            case LUA_TLIGHTUSERDATA:

                *dst++ = 'n';
                *dst++ = 'u';
                *dst++ = 'l';
                *dst++ = 'l';
                break;

            default:
                luaL_error(L, "impossible to reach here");
                return NULL;
        }

        lua_pop(L, 1); /* stack: table */
    }

    return dst;
}
Beispiel #18
0
int
sys_start(int argc, char *argv[])
{
	int status;
	const char* f;
	lua_State *L;
	
	if (argc<2) {
		printf("%s: <filename.lua>\n", argv[0]);
		return 1;
	}
	
    s_init();
    log_print("sound> initialized\n");
	
	L = lua_open();
	/*luaopen_base(L);*/
	luaL_openlibs(L);
	luaopen_sys(L);
	luaopen_log(L);
	luaopen_mat4(L);
	luaopen_quat(L);
	luaopen_vec3(L);
	luaopen_event(L);
	luaopen_image(L);
	luaopen_render(L);
	luaopen_shader(L);
	luaopen_sound(L);
	luaopen_net(L);
	luaopen_util(L);
	luaopen_font(L);
	luaopen_md2(L);
	//luaopen_blender(L);
	
	lua_getglobal(L, "package");
	if (LUA_TTABLE != lua_type(L, 1)) {
		log_print("lua> 'package' is not a table\n");
		return 1;
	}
	lua_getfield(L, 1, "path");
	if (LUA_TSTRING != lua_type(L, 2)) {
		log_print("lua> 'package.path' is not a string\n");
		lua_pop(L, 1);
		return 1;
	}
	lua_pop(L, 1);
	
#if defined(__IPHONE__)
	f = full_path();
#else
	f = ".";
#endif

	/* package.path = f .. "/?.lua" */
	lua_pushlstring(L, f, strlen(f));
	lua_pushliteral(L, "/?.lua");
	lua_concat(L, 2);
	lua_setfield(L, 1, "path");

	lua_bootstrap(L, f);

#if defined(__IPHONE__)
	f = full_path_to_file(argv[1]);
#else
	f = argv[1];
#endif

	log_print("lua> initialized\n");
	printf("lua> loading %s\n", f);
	
	if (luaL_loadfile(L,f)==0) { 
		/* function runme = file_content */
		lua_setglobal(L, "runme");
		lua_getglobal(L, "runme");

		status = lua_pcall(L,0,LUA_MULTRET,0);
		assert(0 == report(L, status));
        
        if (lua_gettop(L) > 0) {
            status = lua_toboolean(L, -1);
            if (!status) {
                printf("lua> %s returned false\n", f);
                sys_quit();
            }
        }
		
        log_print("lua> loaded\n");
	} else {
		printf("lua> unable to load %s\n",f);
		report(L, status);
		sys_quit();
	}

	lua_state = L;
	
	/* TODO: Double check this stuff some day when bored. */
	return status > 0 ? false : true;	
}
Beispiel #19
0
static int getboolfield (lua_State *L, const char *key) {
    int res;
    res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
    lua_pop(L, 1);
    return res;
}
LuaObject LuaTableSelector::toLuaObject( void ) const
{
	magicalAssert( !_key.empty(), "key should not be empty!" );
	if( !_L || !_handler ) 
		return nullptr;

	lua_State* L = _L->cPtr();
	LuaObject lobj;
	tolua_ext_get_table_by_handler( L, _handler );
	lua_getfield( L, -1, _key.c_str() );

	switch( lua_type( L, -1 ) )
	{
	case LUA_TNIL:
		lobj = nullptr;
		break;
	case LUA_TBOOLEAN:
		lobj = (bool) lua_toboolean( L, -1 );
		break;
	case LUA_TNUMBER:
		lobj = (double) lua_tonumber( L, -1 );
		break;
	case LUA_TSTRING:
		lobj = lua_tostring( L, -1 );
		break;
	case LUA_TUSERDATA:
		{
			int top = lua_gettop( L );
			std::string type = tolua_typename( L, top );
			lua_pop( L, 1 );
			void* userdata = tolua_tousertype( L, top, 0 );
			lobj.set( userdata, type.c_str() );
		}
		break;
	case LUA_TFUNCTION:
		{
			LuaFunction lf;
			int handler = tolua_ext_tofunction( L, lua_gettop( L ), 0 );
			if( handler != 0 )
			{
				lf.bind( _L, handler );
			}
			lobj = lf;
		}
		break;
	case LUA_TTABLE:
		{
			LuaTable lt;
			int handler = tolua_ext_totable( L, lua_gettop( L ), 0 );
			if( handler != 0 )
			{
				lt.bind( _L, handler );
			}
			lobj = lt;
		}
		break;
	default:
		lobj = nullptr;
		break;
	}
	lua_pop( L, 1 );
	return lobj;
}
Beispiel #21
0
static int buffer_writeobject(lua_State *L, buffer_t *buf, int idx, struct writer_t *W)
{
	int top = lua_gettop(L);
	int type = lua_type(L, idx);
	switch(type)
	{
		case LUA_TNIL:
			buffer_writebyte(buf, OP_NIL);
			break;
		case LUA_TBOOLEAN:
			buffer_writebyte(buf, lua_toboolean(L, idx) ? OP_TRUE : OP_FALSE);
			break;
		case LUA_TNUMBER:
		{
			lua_Number n = lua_tonumber(L, idx);
			if (n == 0)
				buffer_writebyte(buf, OP_ZERO);
			else if (floor(n) == n)
			{
				size_t size, pos = buffer_tell(buf);
				buffer_writebyte(buf, OP_INT);
				size = buffer_writeint(buf, n);
				*buffer_at(buf, pos) |= size << 4;
			}
			else
			{
				size_t size, pos = buffer_tell(buf);
				buffer_writebyte(buf, OP_FLOAT);
				size = buffer_writefloat(buf, n);
				*buffer_at(buf, pos) |= size << 4;
			}
			break;
		}
		case LUA_TSTRING:
		{
			size_t len;
			const char* str = lua_tolstring(L, idx, &len);
			size_t size, pos = buffer_tell(buf);
			buffer_writebyte(buf, OP_STRING);
			size = buffer_writeint(buf, len);
			*buffer_at(buf, pos) |= size << 4;
			buffer_write(buf, str, len);
			break;
		}
		case LUA_TTABLE:
		{
			const void *ptr = lua_topointer(L, idx);
			size_t i;
			for (i = 0; i < W->count; ++i)
			{
				if (W->refs[i].ptr == ptr)
				{
					buffer_writebyte(buf, OP_TABLE_REF);
					buffer_writebyte(buf, W->refs[i].pos);
					goto end;
				}
			}
			luaL_check(W->count < REFS_SIZE, "table refs overflow %d", REFS_SIZE);
			W->refs[W->count].ptr = ptr;
			W->refs[W->count++].pos = buffer_tell(buf) - W->pos;
			
			buffer_writebyte(buf, OP_TABLE);
			lua_pushnil(L);
			i = 1;
			while (lua_next(L, idx))
			{
				if (lua_isnumber(L, -2) && lua_tonumber(L, -2) == i++)
				{
					buffer_writeobject(L, buf, lua_gettop(L), W);
					lua_pop(L, 1);
				}
				else break;
			}
			buffer_writebyte(buf, OP_TABLE_DELIMITER);
			if (lua_gettop(L) > top)
			{
				do
				{
					buffer_writeobject(L, buf, lua_gettop(L) - 1, W);
					buffer_writeobject(L, buf, lua_gettop(L), W);
					lua_pop(L, 1);
				}
				while (lua_next(L, idx));
			}
			buffer_writebyte(buf, OP_TABLE_END);
			break;
		}
		default:
			lua_settop(L, top);
			luaL_error(L, "unexpected type:%s", lua_typename(L, type));
			return 0;
	}
end:
	lua_settop(L, top);
	return 1;
}
Beispiel #22
0
axl_bool lua_vortex_tls_bridge_accept_handler (VortexConnection * conn, 
					       const char       * serverName)
{
	VortexCtx     * ctx        = CONN_CTX (conn);
	LuaVortexRefs * references = vortex_ctx_get_data (ctx, "lua:tls:accept");
	lua_State     * L          = references->ref->L;
	lua_State     * thread;
	int             initial_top;
	int             error;
	axl_bool        result     = axl_false;

	lua_vortex_log (LUA_VORTEX_DEBUG, "Received notification to bridge accept tls handler (L: %p), marshalling..", L);

	/* create thread to represent this context */
	thread = lua_vortex_create_thread (ctx, L, axl_true);

	/* check if vortex is finish to skip bridging */
	if (vortex_is_exiting (ctx) || thread == NULL)
		return axl_false;

	lua_vortex_log (LUA_VORTEX_DEBUG, "   thread created, acquiring lock ..");

	/* lock during operations */
	LUA_VORTEX_LOCK (L, axl_true);

	lua_vortex_log (LUA_VORTEX_DEBUG, "   lock acquired ..");

	/* check if we are in process of finishing */
	if (vortex_is_exiting (ctx)) {
		lua_vortex_log (LUA_VORTEX_DEBUG, "   found current state finishing ...");

		LUA_VORTEX_UNLOCK (L, axl_true);
		return axl_false;
	}

	/* get new initial top */
	initial_top = lua_gettop (thread);

	lua_vortex_log (LUA_VORTEX_DEBUG, "Found thread %p (top: %d), preparing call..", thread, initial_top);

	/* push the handler to call */
	lua_rawgeti (thread, LUA_REGISTRYINDEX, references->ref->ref_id);

	/* push the connection */
	lua_vortex_connection_new_ref (thread, conn, axl_true);

	/* push serverName */
	lua_pushstring (thread, serverName);

	/* push user data */
	lua_rawgeti (thread, LUA_REGISTRYINDEX, references->ref2->ref_id);

	/* now call */
	lua_vortex_log (LUA_VORTEX_DEBUG, "About to call on accept tls handler on lua space..");
	error = lua_pcall (thread, 3, 1, 0);

	/* handle error */
	lua_vortex_handle_error (thread, error, "on accept tls");

	if (lua_gettop (thread) > 0 && lua_isboolean (thread, -1)) {
		result = lua_toboolean (thread, -1);
		lua_vortex_log (LUA_VORTEX_DEBUG, "lua accept tls handler returned: %d", result);
	} /* end if */

	/* unlock during operations */
	LUA_VORTEX_UNLOCK (L, axl_true);

	return result;
}
Beispiel #23
0
	static int l_set_level_ascending(lua_State *l) {
		UI::Gauge *gauge = LuaObject<UI::Gauge>::CheckFromLua(1);
		gauge->SetLevelAscending(lua_toboolean(l, 2));
		lua_pushvalue(l, 1);
		return 1;
	}
Beispiel #24
0
static int _lua_echo(epdata_t *epd, lua_State *L, int nargs, int can_yield)
{
    size_t len = 0;
    int have = 0;
    epd->next_out = NULL;

    if(lua_istable(L, 1)) {
        len = lua_calc_strlen_in_table(L, 1, 2, 0 /* strict */);

        if(len < 1) {
            return 0;
        }

        char *buf = temp_buf;

        if(len > 8192) {
            buf = malloc(len);

            if(!buf) {
                return 0;
            }

            lua_copy_str_in_table(L, 1, buf);
            have = network_send(epd, buf, len);

            if(have > 0 && can_yield) {
                epd->next_out = malloc(have);
                memcpy(epd->next_out, buf + (len - have), have);
            }

            free(buf);

        } else {
            lua_copy_str_in_table(L, 1, buf);
            have = network_send(epd, buf, len);

            if(have > 0 && can_yield) {
                epd->next_out = malloc(have);
                memcpy(epd->next_out, buf + (len - have), have);
            }
        }

    } else {
        const char *data = NULL;
        int i = 0;

        for(i = 1; i <= nargs; i++) {
            if(lua_isboolean(L, i)) {
                char *buf = NULL;

                if(lua_toboolean(L, i)) {
                    buf = "true";
                    have = network_send(epd, buf, 4);

                } else {
                    buf = "false";
                    have = network_send(epd, buf, 5);
                }

                if(have > 0 && can_yield) {
                    epd->next_out = malloc(have);
                    memcpy(epd->next_out, buf + (len - have), have);
                }

            } else {
                data = lua_tolstring(L, i, &len);
                have = network_send(epd, data, len);

                if(have > 0 && can_yield) {
                    epd->next_out = malloc(have);
                    memcpy(epd->next_out, data + (len - have), have);
                }
            }
        }
    }

    if(epd->next_out) {
        if(network_flush(epd) == 1) {
            epd->next_proc = send_then_send;
            epd->next_out_len = have;
            return have;

        } else {
            LOGF(ERR, "flush error");
            free(epd->next_out);
            epd->next_out = NULL;
            return 0;
        }
    }

    return 0;
}
int LuaStack::executeFunctionReturnArray(int handler,int numArgs,int numResults,Array& resultArray)
{
    if (pushFunctionByHandler(handler))                 /* L: ... arg1 arg2 ... func */
    {
        if (numArgs > 0)
        {
            lua_insert(_state, -(numArgs + 1));         /* L: ... func arg1 arg2 ... */
            int functionIndex = -(numArgs + 1);
            if (!lua_isfunction(_state, functionIndex))
            {
                CCLOG("value at stack [%d] is not function", functionIndex);
                lua_pop(_state, numArgs + 1); // remove function and arguments
                return 0;
            }
            
            int traceback = 0;
            lua_getglobal(_state, "__G__TRACKBACK__");                         /* L: ... func arg1 arg2 ... G */
            if (!lua_isfunction(_state, -1))
            {
                lua_pop(_state, 1);                                            /* L: ... func arg1 arg2 ... */
            }
            else
            {
                lua_insert(_state, functionIndex - 1);                         /* L: ... G func arg1 arg2 ... */
                traceback = functionIndex - 1;
            }
            
            int error = 0;
            ++_callFromLua;
            error = lua_pcall(_state, numArgs, numResults, traceback);                  /* L: ... [G] ret1 ret2 ... retResults*/
            --_callFromLua;
            if (error)
            {
                if (traceback == 0)
                {
                    CCLOG("[LUA ERROR] %s", lua_tostring(_state, - 1));        /* L: ... error */
                    lua_pop(_state, 1); // remove error message from stack
                }
                else                                                            /* L: ... G error */
                {
                    lua_pop(_state, 2); // remove __G__TRACKBACK__ and error message from stack
                }
                return 0;
            }
            
            // get return value,don't pass LUA_MULTRET to numResults,
            if (numResults <= 0)
                return 0;
            
            for (int i = 0 ; i < numResults; i++)
            {
                if (lua_type(_state, -1) == LUA_TBOOLEAN) {
                    
                    bool value = lua_toboolean(_state, -1);
                    resultArray.addObject(Bool::create(value)) ;
                    
                }else if (lua_type(_state, -1) == LUA_TNUMBER) {
                    
                    double value = lua_tonumber(_state, -1);
                    resultArray.addObject(Double::create(value));
                    
                }else if (lua_type(_state, -1) == LUA_TSTRING) {
                    
                    const char* value = lua_tostring(_state, -1);
                    resultArray.addObject(String::create(value));
                    
                }else{
                    
                    resultArray.addObject(static_cast<Ref*>(tolua_tousertype(_state, -1, NULL)));
                }
                // remove return value from stack
                lua_pop(_state, 1);                                                /* L: ... [G] ret1 ret2 ... ret*/
            }
            /* L: ... [G]*/
            
            if (traceback)
            {
                lua_pop(_state, 1); // remove __G__TRACKBACK__ from stack      /* L: ... */
            }
        }
    }
    lua_settop(_state, 0);
    return 1;
}
Beispiel #26
0
static int l_soundfx_set_sound_effects_on(lua_State *L)
{
    THSoundEffects *pEffects = luaT_testuserdata<THSoundEffects>(L);
    pEffects->setSoundEffectsOn(lua_toboolean(L, 2) != 0);
    return 1;
}
Beispiel #27
0
void LuaSerializer::pickle(lua_State *l, int to_serialize, std::string &out, std::string key)
{
	static char buf[256];

	LUA_DEBUG_START(l);

	// tables are pickled recursively, so we can run out of Lua stack space if we're not careful
	// start by ensuring we have enough (this grows the stack if necessary)
	// (20 is somewhat arbitrary)
	if (!lua_checkstack(l, 20))
		luaL_error(l, "The Lua stack couldn't be extended (out of memory?)");

	to_serialize = lua_absindex(l, to_serialize);
	int idx = to_serialize;

	if (lua_getmetatable(l, idx)) {
		lua_getfield(l, -1, "class");
		if (lua_isnil(l, -1))
			lua_pop(l, 2);

		else {
			const char *cl = lua_tostring(l, -1);
			snprintf(buf, sizeof(buf), "o%s\n", cl);

			lua_getfield(l, LUA_REGISTRYINDEX, "PiSerializerClasses");

			lua_getfield(l, -1, cl);
			if (lua_isnil(l, -1))
				luaL_error(l, "No Serialize method found for class '%s'\n", cl);

			lua_getfield(l, -1, "Serialize");
			if (lua_isnil(l, -1))
				luaL_error(l, "No Serialize method found for class '%s'\n", cl);

			lua_pushvalue(l, idx);
			pi_lua_protected_call(l, 1, 1);

			idx = lua_gettop(l);

			if (lua_isnil(l, idx)) {
				lua_pop(l, 5);
				LUA_DEBUG_END(l, 0);
				return;
			}

			out += buf;
		}
	}

	switch (lua_type(l, idx)) {
		case LUA_TNIL:
			break;

		case LUA_TNUMBER: {
			snprintf(buf, sizeof(buf), "f%f\n", lua_tonumber(l, idx));
			out += buf;
			break;
		}

		case LUA_TBOOLEAN: {
			snprintf(buf, sizeof(buf), "b%d", lua_toboolean(l, idx) ? 1 : 0);
			out += buf;
			break;
		}

		case LUA_TSTRING: {
			lua_pushvalue(l, idx);
			size_t len;
			const char *str = lua_tolstring(l, -1, &len);
			snprintf(buf, sizeof(buf), "s" SIZET_FMT "\n", len);
			out += buf;
			out.append(str, len);
			lua_pop(l, 1);
			break;
		}

		case LUA_TTABLE: {
			lua_pushinteger(l, lua_Integer(lua_topointer(l, to_serialize)));         // ptr

			lua_getfield(l, LUA_REGISTRYINDEX, "PiSerializerTableRefs");    // ptr reftable
			lua_pushvalue(l, -2);                                           // ptr reftable ptr
			lua_rawget(l, -2);                                              // ptr reftable ???

			if (!lua_isnil(l, -1)) {
				out += "r";
				pickle(l, -3, out, key);
				lua_pop(l, 3);                                              // [empty]
			}

			else {
				out += "t";

				lua_pushvalue(l, -3);                                       // ptr reftable nil ptr
				lua_pushvalue(l, to_serialize);                                      // ptr reftable nil ptr table
				lua_rawset(l, -4);                                          // ptr reftable nil
				pickle(l, -3, out, key);
				lua_pop(l, 3);                                              // [empty]

				lua_pushvalue(l, idx);
				lua_pushnil(l);
				while (lua_next(l, -2)) {

					lua_pushvalue(l, -2);
					const char *k = lua_tostring(l, -1);
					std::string new_key = key + "." + (k? std::string(k) : "<" + std::string(lua_typename(l, lua_type(l, -1))) + ">");
					lua_pop(l, 1);

					// Copy the values to pickle, as they might be mutated by the pickling process.
					pickle(l, -2, out, new_key);
					pickle(l, -1, out, new_key);
					lua_pop(l, 1);
				}
				lua_pop(l, 1);
				out += "n";
			}

			break;
		}

		case LUA_TUSERDATA: {
			out += "u";

			LuaObjectBase *lo = static_cast<LuaObjectBase*>(lua_touserdata(l, idx));
			void *o = lo->GetObject();
			if (!o)
				Error("Lua serializer '%s' tried to serialize an invalid '%s' object", key.c_str(), lo->GetType());

			out += lo->Serialize();
			break;
		}

		default:
			Error("Lua serializer '%s' tried to serialize %s value", key.c_str(), lua_typename(l, lua_type(l, idx)));
			break;
	}

	if (idx != lua_absindex(l, to_serialize)) // It means we called a transformation function on the data, so we clean it up.
		lua_pop(l, 5);

	LUA_DEBUG_END(l, 0);
}
Beispiel #28
0
/* args-opts -- proc/nil error */
static int ex_spawn(lua_State *L)
{
  struct spawn_params *params;
  int have_options;
  switch (lua_type(L, 1)) {
  default: return luaL_typerror(L, 1, "string or table");
  case LUA_TSTRING:
    switch (lua_type(L, 2)) {
    default: return luaL_typerror(L, 2, "table");
    case LUA_TNONE: have_options = 0; break;
    case LUA_TTABLE: have_options = 1; break;
    }
    break;
  case LUA_TTABLE:
    have_options = 1;
	/* avoid issues with strict.lua */
	lua_pushstring(L, "command");		/* opts ... cmd */
	lua_rawget(L, 1);
    if (!lua_isnil(L, -1)) {
      /* convert {command=command,arg1,...} to command {arg1,...} */
      lua_insert(L, 1);                 /* cmd opts ... */
    }
    else {
      /* convert {arg0,arg1,...} to arg0 {arg1,...} */
      size_t i, n = lua_objlen(L, 1);
      lua_rawgeti(L, 1, 1);             /* opts ... nil cmd */
      lua_insert(L, 1);                 /* cmd opts ... nil */
      for (i = 2; i <= n; i++) {
        lua_rawgeti(L, 2, i);           /* cmd opts ... nil argi */
        lua_rawseti(L, 2, i - 1);       /* cmd opts ... nil */
      }
      lua_rawseti(L, 2, n);             /* cmd opts ... */
    }
    if (lua_type(L, 1) != LUA_TSTRING)
      return luaL_error(L, "bad command option (string expected, got %s)",
                        luaL_typename(L, 1));
    break;
  }
  params = spawn_param_init(L);
  /* get filename to execute */
  spawn_param_filename(params);
  /* get arguments, environment, and redirections */
  if (have_options) {
    lua_getfield(L, 2, "args");         /* cmd opts ... argtab */
    switch (lua_type(L, -1)) {
    default:
      return luaL_error(L, "bad args option (table expected, got %s)",
                        luaL_typename(L, -1));
    case LUA_TNIL:
      lua_pop(L, 1);                    /* cmd opts ... */
      lua_pushvalue(L, 2);              /* cmd opts ... opts */
      if (0) /*FALLTHRU*/
    case LUA_TTABLE:
      if (lua_objlen(L, 2) > 0)
        return
          luaL_error(L, "cannot specify both the args option and array values");
      spawn_param_args(params);         /* cmd opts ... */
      break;
    }
    lua_getfield(L, 2, "env");          /* cmd opts ... envtab */
    switch (lua_type(L, -1)) {
    default:
      return luaL_error(L, "bad env option (table expected, got %s)",
                        luaL_typename(L, -1));
    case LUA_TNIL:
      break;
    case LUA_TTABLE:
      spawn_param_env(params);          /* cmd opts ... */
      break;
    }

    lua_getfield(L, 2, "show");          /* cmd opts ... envtab */
    spawn_param_show(params, lua_type(L, -1) == LUA_TBOOLEAN ? lua_toboolean(L, -1) : 0);

    lua_getfield(L, 2, "shell");          /* cmd opts ... envtab */
    spawn_param_useshell(params, lua_type(L, -1) == LUA_TBOOLEAN ? lua_toboolean(L, -1) : 1);

    get_redirect(L, 2, "stdin", params);    /* cmd opts ... */
    get_redirect(L, 2, "stdout", params);   /* cmd opts ... */
    get_redirect(L, 2, "stderr", params);   /* cmd opts ... */
  }
  return spawn_param_execute(params);   /* proc/nil error */
}
Beispiel #29
0
void lua_load_room() {
    /* 运行脚本 */
    int err = luaL_dofile(L, "conf/room.conf");
    if (err) {
        //如果错误,显示
        log_write(LOG_ERR, lua_tostring(L, -1), __FILE__, __LINE__);
        return;
    }

    /* 获取变量 */
    lua_getglobal(L, "rooms");

    int l = lua_gettop(L);

    int len = lua_objlen(L, l); //下标从1开始的,如果从0开始,要+1

    printf("lua_load_room n:%d,num:%d\n", l, lua_objlen(L, l));
    printf("lua_load_room -n:%d,num:%d\n", l, lua_objlen(L, -1));

    if (lua_istable(L, -1)) {
        int i = 0;
        printf("[table] %d\n", l);
        lua_pushnil(L);
        //lua_rawgeti(L, 1, i); lua_isstring(L, -1)
        while (lua_next(L, -2) && i < MAX_ROOMS) {
            switch (lua_type(L, -1)) {
                case LUA_TNIL:
                    printf("[nil] nil\n");
                    break;
                case LUA_TBOOLEAN:
                    printf("[boolean] %s\n", lua_toboolean(L, -1) ? "true" : "false");
                    break;
                case LUA_TLIGHTUSERDATA:
                    printf("[lightuserdata] 0x%x\n", (int) lua_topointer(L, -1));
                    break;
                case LUA_TNUMBER:
                    printf("[number] %f\n", lua_tonumber(L, -1));
                    break;
                case LUA_TSTRING:
                    i++;
                    printf("[string] %s\n", lua_tostring(L, -1));
                    rooms[i].enable = 1;
                    strncpy(rooms[i].name, lua_tostring(L, -1), MAX_CHAR_LENGTH);
                    break;
                case LUA_TTABLE:
                    printf("[table]\n");
                    break;
                case LUA_TFUNCTION:
                    printf("[function] 0x%x\n", (int) lua_topointer(L, -1));
                    break;
                case LUA_TUSERDATA:
                    printf("userdata] 0x%x\n", (int) lua_topointer(L, -1));
                    break;
                case LUA_TTHREAD:
                    printf("[thread] 0x%x\n", (int) lua_topointer(L, -1));
                    break;
                default:
                    printf("[none]\n");
            }
            lua_pop(L, 1);
        }
    } else {
        printf("lua_istable(L, -1) 返回 false\n");
    }
}
Beispiel #30
0
static int FeatureDefNewIndex(lua_State* L)
{
	// not a default value, set it
	if (!lua_isstring(L, 2)) {
		lua_rawset(L, 1);
		return 0;
	}

	const char* name = lua_tostring(L, 2);
	ParamMap::const_iterator it = paramMap.find(name);

	// not a default value, set it
	if (it == paramMap.end()) {
		lua_rawset(L, 1);
		return 0;
	}

	const void* userData = lua_touserdata(L, lua_upvalueindex(1));
	const FeatureDef* fd = static_cast<const FeatureDef*>(userData);

	// write-protected
	if (!gs->editDefsEnabled) {
		luaL_error(L, "Attempt to write FeatureDefs[%d].%s", fd->id, name);
		return 0;
	}

	// Definition editing
	const DataElement& elem = it->second;
	const char* p = ((const char*)fd) + elem.offset;

	switch (elem.type) {
		case FUNCTION_TYPE:
		case READONLY_TYPE: {
			luaL_error(L, "Can not write to %s", name);
			return 0;
		}
		case INT_TYPE: {
			*((int*)p) = lua_toint(L, -1);
			return 0;
		}
		case BOOL_TYPE: {
			*((bool*)p) = lua_toboolean(L, -1);
			return 0;
		}
		case FLOAT_TYPE: {
			*((float*)p) = lua_tofloat(L, -1);
			return 0;
		}
		case STRING_TYPE: {
			*((string*)p) = lua_tostring(L, -1);
			return 0;
		}
		case ERROR_TYPE: {
			LOG_L(L_ERROR, "[%s] ERROR_TYPE for key \"%s\" in FeatureDefs __newindex", __FUNCTION__, name);
			lua_pushnil(L);
			return 1;
		}
	}

	return 0;
}