Ejemplo n.º 1
0
// mysdb :serialize_cancel()
static int api_serialize_cancel( lua_State *L) {
    int r = sdb_serialize_cancel( lua_sdb_checktable( L, 1));
    lua_settop( L, 1); // in case of extra args
    lua_pushinteger( L, r); // no lua_error, just a status
    return 2; // push table back
}
Ejemplo n.º 2
0
void Eluna::BeginCall(int fReference)
{
    lua_settop(LuaState, 0); //stack should be empty
    lua_rawgeti(LuaState, LUA_REGISTRYINDEX, (fReference));
}
int lua_cocos2dx_spine_SkeletonAnimation_clearTrack(lua_State* tolua_S)
{
    int argc = 0;
    spine::SkeletonAnimation* cobj = nullptr;
    bool ok  = true;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
#endif


#if COCOS2D_DEBUG >= 1
    if (!tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err)) goto tolua_lerror;
#endif

    cobj = (spine::SkeletonAnimation*)tolua_tousertype(tolua_S,1,0);

#if COCOS2D_DEBUG >= 1
    if (!cobj) 
    {
        tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_spine_SkeletonAnimation_clearTrack'", nullptr);
        return 0;
    }
#endif

    argc = lua_gettop(tolua_S)-1;
    if (argc == 0) 
    {
        if(!ok)
        {
            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_spine_SkeletonAnimation_clearTrack'", nullptr);
            return 0;
        }
        cobj->clearTrack();
        lua_settop(tolua_S, 1);
        return 1;
    }
    if (argc == 1) 
    {
        int arg0;

        ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "sp.SkeletonAnimation:clearTrack");
        if(!ok)
        {
            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_spine_SkeletonAnimation_clearTrack'", nullptr);
            return 0;
        }
        cobj->clearTrack(arg0);
        lua_settop(tolua_S, 1);
        return 1;
    }
    luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "sp.SkeletonAnimation:clearTrack",argc, 0);
    return 0;

#if COCOS2D_DEBUG >= 1
    tolua_lerror:
    tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_spine_SkeletonAnimation_clearTrack'.",&tolua_err);
#endif

    return 0;
}
Ejemplo n.º 4
0
/*******************************************************************************
	FUNCTION CALL METHODS
*******************************************************************************/
void LuaEngine::BeginCall(uint16 fReference)
{
    lua_settop(L, 0); //stack should be empty
    lua_getref(L, fReference);
}
Ejemplo n.º 5
0
TOLUA_API void tolua_open (lua_State* L)
{
    int top = lua_gettop(L);
    lua_pushstring(L,"tolua_opened");
    lua_rawget(L,LUA_REGISTRYINDEX);
    if (!lua_isboolean(L,-1))
    {
        lua_pushstring(L,"tolua_opened");
        lua_pushboolean(L,1);
        lua_rawset(L,LUA_REGISTRYINDEX);
        
        
        /** create value root table
         */
        lua_pushstring(L, TOLUA_VALUE_ROOT);
        lua_newtable(L);
        lua_rawset(L, LUA_REGISTRYINDEX);

#ifndef LUA_VERSION_NUM /* only prior to lua 5.1 */
        /* create peer object table */
        lua_pushstring(L, "tolua_peers");
        lua_newtable(L);
        /* make weak key metatable for peers indexed by userdata object */
        lua_newtable(L);
        lua_pushliteral(L, "__mode");
        lua_pushliteral(L, "k");
        lua_rawset(L, -3);                /* stack: string peers mt */
        lua_setmetatable(L, -2);   /* stack: string peers */
        lua_rawset(L,LUA_REGISTRYINDEX);
#endif

        /* create object ptr -> udata mapping table */
        lua_pushstring(L,"tolua_ubox");
        lua_newtable(L);
        /* make weak value metatable for ubox table to allow userdata to be
           garbage-collected */
        lua_newtable(L);
        lua_pushliteral(L, "__mode");
        lua_pushliteral(L, "v");
        lua_rawset(L, -3);               /* stack: string ubox mt */
        lua_setmetatable(L, -2);  /* stack: string ubox */
        lua_rawset(L,LUA_REGISTRYINDEX);
        
//        /* create object ptr -> class type mapping table */
//        lua_pushstring(L, "tolua_ptr2type");
//        lua_newtable(L);
//        lua_rawset(L, LUA_REGISTRYINDEX);

        lua_pushstring(L,"tolua_super");
        lua_newtable(L);
        lua_rawset(L,LUA_REGISTRYINDEX);
        lua_pushstring(L,"tolua_gc");
        lua_newtable(L);
        lua_rawset(L,LUA_REGISTRYINDEX);

        /* create gc_event closure */
        lua_pushstring(L, "tolua_gc_event");
        lua_pushstring(L, "tolua_gc");
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_pushstring(L, "tolua_super");
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_pushcclosure(L, class_gc_event, 2);
        lua_rawset(L, LUA_REGISTRYINDEX);

        tolua_newmetatable(L,"tolua_commonclass");

        tolua_module(L,NULL,0);
        tolua_beginmodule(L,NULL);
        tolua_module(L,"tolua",0);
        tolua_beginmodule(L,"tolua");
        tolua_function(L,"type",tolua_bnd_type);
        tolua_function(L,"takeownership",tolua_bnd_takeownership);
        tolua_function(L,"releaseownership",tolua_bnd_releaseownership);
        tolua_function(L,"cast",tolua_bnd_cast);
        tolua_function(L,"isnull",tolua_bnd_isnulluserdata);
        tolua_function(L,"inherit", tolua_bnd_inherit);
#ifdef LUA_VERSION_NUM /* lua 5.1 */
        tolua_function(L, "setpeer", tolua_bnd_setpeer);
        tolua_function(L, "getpeer", tolua_bnd_getpeer);
#endif

        tolua_endmodule(L);
        tolua_endmodule(L);
    }
    lua_settop(L,top);
}
Ejemplo n.º 6
0
// TODO
// getters
int LTreeView::getViewport ( lua_State* ) {
    // return LUA::TODO_RETURN_OBJECT_Viewport( TreeView::getViewport() );
    lua_settop(LUA::Get(), 1); // added by TODO
    return LUA::TODO_OBJECT( "Viewport getViewport()" );
}
Ejemplo n.º 7
0
void CDebugHelper::printValue(lua_State* pState, const char* value)
{
    char buffer[1024];
    int top = lua_gettop(pState);

    char sep[] = ".[]";
    char* next = NULL;
    char* last = NULL;

    bool found = false;

    strcpy(buffer, value);

    lua_Debug ar;
    lua_getstack(pState, m_curFrame, &ar);

    next = strtok_r(buffer, sep, &last);

    do
    {
        for(int i = 1;;i++)
        {
            const char* key = lua_getlocal(pState, &ar, i);
            if(!key)
            {
                break;
            }

            if(strcmp(key, next) == 0)
            {
                found = true;
                break;
            }
            else
            {
                lua_pop(pState, 1);
            }
        }

        if (found)
        {
            break;
        }

        lua_getinfo(pState, "f", &ar);
        int funcIndex = lua_gettop(pState);
        for (int i = 1; ; i++)
        {
            const char* key = lua_getupvalue(pState, funcIndex, i);
            if (!key)
            {
                break;
            }

            if (strcmp(key, next) == 0)
            {
                found = true;
                break;
            }
            else
            {
                lua_pop(pState, 1);
            }
        }

        if (found)
        {
            break;
        }

        lua_getglobal(pState, next);
        if (lua_isnil(pState, -1))
        {
            lua_pop(pState, 1);
        }
        else
        {
            found = true;
        }
    }while(0);

    if (!found)
    {
        printf("nil value\n");
    }
    else
    {
        while(true)
        {
            if (lua_isnil(pState, -1))
            {
                printf("nil value\n");
                break;
            }
            next = strtok_r(NULL, sep, &last);
            if(!next)
            {
                printStackValue(pState, -1);
                break;
            }
            else
            {
                bool isNumber = true;
                int len = strlen(next);
                for (int i = 0; i < len; ++i)
                {
                    if (!isdigit(next[i]))
                    {
                        isNumber = false;
                        break;
                    }
                }

                if (isNumber)
                {
                    lua_pushnumber(pState, atoi(next));
                }
                else
                {
                    if(next[0] == '"' && next[len - 1] == '"')
                    {
                        next[len - 1] = '\0';
                        lua_pushstring(pState, next + 1);
                    }
                    else
                    {
                        lua_pushstring(pState, next);                        
                    }
                }

                lua_gettable(pState, -2);
                continue;
            }
        }
    }

    lua_settop(pState, top);
}
Ejemplo n.º 8
0
void ScreenTextEntry::TextEntrySettings::FromStack( lua_State *L )
{
	if( lua_type(L, 1) != LUA_TTABLE )
	{
		LOG->Trace("not a table");
		return;
	}

	lua_pushvalue( L, 1 );
	const int iTab = lua_gettop( L );

	// Get ScreenMessage
	lua_getfield( L, iTab, "SendOnPop" );
	const char *pStr = lua_tostring( L, -1 );
	if( pStr == NULL )
		smSendOnPop = SM_None;
	else
		smSendOnPop = ScreenMessageHelpers::ToScreenMessage( pStr );
	lua_settop( L, iTab );

	// Get Question
	lua_getfield( L, iTab, "Question" );
	pStr = lua_tostring( L, -1 );
	if( pStr == NULL )
		RageException::Throw( "\"Question\" entry is not a string." );
	sQuestion = pStr;
	lua_settop( L, iTab );

	// Get Initial Answer
	lua_getfield( L, iTab, "InitialAnswer" );
	pStr = lua_tostring( L, -1 );
	if( pStr == NULL )
		pStr = "";
	sInitialAnswer = pStr;
	lua_settop( L, iTab );

	// Get Max Input Length
	lua_getfield( L, iTab, "MaxInputLength" );
	iMaxInputLength = lua_tointeger( L, -1 );
	lua_settop( L, iTab );

	// Get Password
	lua_getfield( L, iTab, "Password" );
	bPassword = !!lua_toboolean( L, -1 );
	lua_settop( L, iTab );

	// and now the hard part, the functions.
	// Validate
	lua_getfield( L, iTab, "Validate" );
	if( !lua_isfunction( L, -1 ) && !lua_isnil( L, -1 ) )
		RageException::Throw( "\"Validate\" is not a function." );
	Validate.SetFromStack( L );
	lua_settop( L, iTab );

	// OnOK
	lua_getfield( L, iTab, "OnOK" );
	if( !lua_isfunction( L, -1 ) && !lua_isnil( L, -1 ) )
		RageException::Throw( "\"OnOK\" is not a function." );
	OnOK.SetFromStack( L );
	lua_settop( L, iTab );

	// OnCancel
	lua_getfield( L, iTab, "OnCancel" );
	if( !lua_isfunction( L, -1 ) && !lua_isnil( L, -1 ) )
		RageException::Throw( "\"OnCancel\" is not a function." );
	OnCancel.SetFromStack( L );
	lua_settop( L, iTab );

	// ValidateAppend
	lua_getfield( L, iTab, "ValidateAppend" );
	if( !lua_isfunction( L, -1 ) && !lua_isnil( L, -1 ) )
		RageException::Throw( "\"ValidateAppend\" is not a function." );
	ValidateAppend.SetFromStack( L );
	lua_settop( L, iTab );

	// FormatAnswerForDisplay
	lua_getfield( L, iTab, "FormatAnswerForDisplay" );
	if( !lua_isfunction( L, -1 ) && !lua_isnil( L, -1 ) )
		RageException::Throw( "\"FormatAnswerForDisplay\" is not a function." );
	FormatAnswerForDisplay.SetFromStack( L );
	lua_settop( L, iTab );
}
Ejemplo n.º 9
0
void LuaStack::clean(void)
{
    lua_settop(_state, 0);
}
static ngx_int_t
ngx_http_lua_balancer_by_chunk(lua_State *L, ngx_http_request_t *r)
{
    u_char                  *err_msg;
    size_t                   len;
    ngx_int_t                rc;
    ngx_http_lua_ctx_t      *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);

    if (ctx == NULL) {
        ctx = ngx_http_lua_create_ctx(r);
        if (ctx == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

    } else {
        dd("reset ctx");
        ngx_http_lua_reset_ctx(r, L, ctx);
    }

    ctx->context = NGX_HTTP_LUA_CONTEXT_BALANCER;

    /* init nginx context in Lua VM */
    ngx_http_lua_set_req(L, r);
    ngx_http_lua_create_new_globals_table(L, 0 /* narr */, 1 /* nrec */);

    /*  {{{ make new env inheriting main thread's globals table */
    lua_createtable(L, 0, 1 /* nrec */);   /* the metatable for the new env */
    ngx_http_lua_get_globals_table(L);
    lua_setfield(L, -2, "__index");
    lua_setmetatable(L, -2);    /*  setmetatable({}, {__index = _G}) */
    /*  }}} */

    lua_setfenv(L, -2);    /*  set new running env for the code closure */

    lua_pushcfunction(L, ngx_http_lua_traceback);
    lua_insert(L, 1);  /* put it under chunk and args */

    /*  protected call user code */
    rc = lua_pcall(L, 0, 1, 1);

    lua_remove(L, 1);  /* remove traceback function */

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

    if (rc != 0) {
        /*  error occured when running loaded code */
        err_msg = (u_char *) lua_tolstring(L, -1, &len);

        if (err_msg == NULL) {
            err_msg = (u_char *) "unknown reason";
            len = sizeof("unknown reason") - 1;
        }

        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                      "failed to run balancer_by_lua*: %*s", len, err_msg);

        lua_settop(L, 0); /*  clear remaining elems on stack */

        return NGX_ERROR;
    }

    lua_settop(L, 0); /*  clear remaining elems on stack */
    return rc;
}
int LuaStack::luaLoadChunksFromZIP(lua_State *L)
{
    if (lua_gettop(L) < 1) {
        CCLOG("luaLoadChunksFromZIP() - invalid arguments");
        return 0;
    }
    
    const char *zipFilename = lua_tostring(L, -1);
    lua_settop(L, 0);
    FileUtils *utils = FileUtils::getInstance();
    std::string zipFilePath = utils->fullPathForFilename(zipFilename);
    
    LuaStack *stack = this;
    
    do {
        ssize_t size = 0;
        void *buffer = nullptr;
        unsigned char *zipFileData = utils->getFileData(zipFilePath.c_str(), "rb", &size);
        ZipFile *zip = nullptr;
        
        bool isXXTEA = stack && stack->_xxteaEnabled && zipFileData;
        for (int i = 0; isXXTEA && i < stack->_xxteaSignLen && i < size; ++i) {
            isXXTEA = zipFileData[i] == stack->_xxteaSign[i];
        }
        
        if (isXXTEA) { // decrypt XXTEA
            xxtea_long len = 0;
            buffer = xxtea_decrypt(zipFileData + stack->_xxteaSignLen,
                                   (xxtea_long)size - (xxtea_long)stack->_xxteaSignLen,
                                   (unsigned char*)stack->_xxteaKey,
                                   (xxtea_long)stack->_xxteaKeyLen,
                                   &len);
            free(zipFileData);
            zipFileData = nullptr;
            zip = ZipFile::createWithBuffer(buffer, len);
        } else {
            if (zipFileData) {
                zip = ZipFile::createWithBuffer(zipFileData, size);
            }
        }
        
        if (zip) {
            CCLOG("lua_loadChunksFromZIP() - load zip file: %s%s", zipFilePath.c_str(), isXXTEA ? "*" : "");
            lua_getglobal(L, "package");
            lua_getfield(L, -1, "preload");
            
            int count = 0;
            std::string filename = zip->getFirstFilename();
            while (filename.length()) {
                ssize_t bufferSize = 0;
                unsigned char *zbuffer = zip->getFileData(filename.c_str(), &bufferSize);
                if (bufferSize) {
                    // remove extension
                    std::size_t found = filename.rfind(".lua");
                    if (found != std::string::npos)
                    {
                        filename.erase(found);
                    }
                    // replace path seperator '/' '\' to '.'
                    for (int i=0; i<filename.size(); i++) {
                        if (filename[i] == '/' || filename[i] == '\\') {
                            filename[i] = '.';
                        }
                    }
                    CCLOG("[luaLoadChunksFromZIP] add %s to preload", filename.c_str());
                    if (stack->luaLoadBuffer(L, (char*)zbuffer, (int)bufferSize, filename.c_str()) == 0) {
                        lua_setfield(L, -2, filename.c_str());
                        ++count;
                    }
                    free(zbuffer);
                }
                filename = zip->getNextFilename();
            }
            CCLOG("lua_loadChunksFromZIP() - loaded chunks count: %d", count);
            lua_pop(L, 2);
            lua_pushboolean(L, 1);
            
            delete zip;
        } else {
            CCLOG("lua_loadChunksFromZIP() - not found or invalid zip file: %s", zipFilePath.c_str());
            lua_pushboolean(L, 0);
        }
        
        if (zipFileData) {
            free(zipFileData);
        }
        
        if (buffer) {
            free(buffer);
        }
    } while (0);
    
    return 1;
}
Ejemplo n.º 12
0
bool CUnsyncedLuaHandle::Init(const string& code, const string& file)
{
	if (!IsValid()) {
		return false;
	}

	// load the standard libraries
	LUA_OPEN_LIB(L, luaopen_base);
	LUA_OPEN_LIB(L, luaopen_math);
	LUA_OPEN_LIB(L, luaopen_table);
	LUA_OPEN_LIB(L, luaopen_string);
	//LUA_OPEN_LIB(L, luaopen_io);
	//LUA_OPEN_LIB(L, luaopen_os);
	//LUA_OPEN_LIB(L, luaopen_package);
	//LUA_OPEN_LIB(L, luaopen_debug);

	// delete some dangerous functions
	lua_pushnil(L); lua_setglobal(L, "dofile");
	lua_pushnil(L); lua_setglobal(L, "loadfile");
	lua_pushnil(L); lua_setglobal(L, "loadlib");
	lua_pushnil(L); lua_setglobal(L, "loadstring"); // replaced
	lua_pushnil(L); lua_setglobal(L, "require");

	lua_pushvalue(L, LUA_GLOBALSINDEX);

	AddBasicCalls(L);

	// remove Script.Kill()
	lua_getglobal(L, "Script");
		LuaPushNamedNil(L, "Kill");
	lua_pop(L, 1);

	LuaPushNamedCFunc(L, "loadstring", CLuaHandleSynced::LoadStringData);
	LuaPushNamedCFunc(L, "CallAsTeam", CLuaHandleSynced::CallAsTeam);
	LuaPushNamedNumber(L, "COBSCALE",  COBSCALE);

	// load our libraries
	if (!LuaSyncedTable::PushEntries(L)                                    ||
	    !AddEntriesToTable(L, "VFS",         LuaVFS::PushUnsynced)         ||
	    !AddEntriesToTable(L, "VFS",         LuaZipFileReader::PushUnsynced) ||
	    !AddEntriesToTable(L, "VFS",         LuaZipFileWriter::PushUnsynced) ||
	    !AddEntriesToTable(L, "UnitDefs",    LuaUnitDefs::PushEntries)     ||
	    !AddEntriesToTable(L, "WeaponDefs",  LuaWeaponDefs::PushEntries)   ||
	    !AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries)  ||
	    !AddEntriesToTable(L, "Script",      LuaInterCall::PushEntriesUnsynced) ||
	    !AddEntriesToTable(L, "Script",      LuaScream::PushEntries)       ||
	    !AddEntriesToTable(L, "Spring",      LuaSyncedRead::PushEntries)   ||
	    !AddEntriesToTable(L, "Spring",      LuaUnsyncedCtrl::PushEntries) ||
	    !AddEntriesToTable(L, "Spring",      LuaUnsyncedRead::PushEntries) ||
	    !AddEntriesToTable(L, "gl",          LuaOpenGL::PushEntries)       ||
	    !AddEntriesToTable(L, "GL",          LuaConstGL::PushEntries)      ||
	    !AddEntriesToTable(L, "Game",        LuaConstGame::PushEntries)    ||
	    !AddEntriesToTable(L, "CMD",         LuaConstCMD::PushEntries)     ||
	    !AddEntriesToTable(L, "CMDTYPE",     LuaConstCMDTYPE::PushEntries) ||
	    !AddEntriesToTable(L, "LOG",         LuaUtils::PushLogEntries)
	) {
		KillLua();
		return false;
	}

	lua_settop(L, 0);

	// add code from the sub-class
	if (!base.AddUnsyncedCode(L)) {
		KillLua();
		return false;
	}

	lua_settop(L, 0);
	if (!LoadCode(L, code, file)) {
		KillLua();
		return false;
	}

	lua_settop(L, 0);
	eventHandler.AddClient(this);
	return true;
}
Ejemplo n.º 13
0
bool CSyncedLuaHandle::Init(const string& code, const string& file)
{
	if (!IsValid())
		return false;

	watchUnitDefs.resize(unitDefHandler->unitDefs.size() + 1, false);
	watchFeatureDefs.resize(featureHandler->GetFeatureDefs().size(), false);
	watchWeaponDefs.resize(weaponDefHandler->weaponDefs.size(), false);

	// load the standard libraries
	LUA_OPEN_LIB(L, luaopen_base);
	LUA_OPEN_LIB(L, luaopen_math);
	LUA_OPEN_LIB(L, luaopen_table);
	LUA_OPEN_LIB(L, luaopen_string);
	//LUA_OPEN_LIB(L, luaopen_io);
	//LUA_OPEN_LIB(L, luaopen_os);
	//LUA_OPEN_LIB(L, luaopen_package);
	//LUA_OPEN_LIB(L, luaopen_debug);

	lua_getglobal(L, "next");
	origNextRef = luaL_ref(L, LUA_REGISTRYINDEX);

	// delete/replace some dangerous functions
	lua_pushnil(L); lua_setglobal(L, "dofile");
	lua_pushnil(L); lua_setglobal(L, "loadfile");
	lua_pushnil(L); lua_setglobal(L, "loadlib");
	lua_pushnil(L); lua_setglobal(L, "require");
	lua_pushnil(L); lua_setglobal(L, "rawequal"); //FIXME not unsafe anymore since split?
	lua_pushnil(L); lua_setglobal(L, "rawget"); //FIXME not unsafe anymore since split?
	lua_pushnil(L); lua_setglobal(L, "rawset"); //FIXME not unsafe anymore since split?
//	lua_pushnil(L); lua_setglobal(L, "getfenv");
//	lua_pushnil(L); lua_setglobal(L, "setfenv");
	lua_pushnil(L); lua_setglobal(L, "newproxy"); // sync unsafe cause of __gc
	lua_pushnil(L); lua_setglobal(L, "gcinfo");
	lua_pushnil(L); lua_setglobal(L, "collectgarbage");

	lua_pushvalue(L, LUA_GLOBALSINDEX);
	LuaPushNamedCFunc(L, "loadstring", CLuaHandleSynced::LoadStringData);
	LuaPushNamedCFunc(L, "pairs", SyncedPairs);
	LuaPushNamedCFunc(L, "next",  SyncedNext);
	lua_pop(L, 1);

	lua_pushvalue(L, LUA_GLOBALSINDEX);

	AddBasicCalls(L); // into Global

	// adjust the math.random() and math.randomseed() calls
	lua_getglobal(L, "math");
		LuaPushNamedCFunc(L, "random", SyncedRandom);
		LuaPushNamedCFunc(L, "randomseed", SyncedRandomSeed);
	lua_pop(L, 1); // pop the global math table

	lua_getglobal(L, "Script");
		LuaPushNamedCFunc(L, "AddActionFallback",    AddSyncedActionFallback);
		LuaPushNamedCFunc(L, "RemoveActionFallback", RemoveSyncedActionFallback);
		LuaPushNamedCFunc(L, "GetWatchUnit",         GetWatchUnitDef);
		LuaPushNamedCFunc(L, "SetWatchUnit",         SetWatchUnitDef);
		LuaPushNamedCFunc(L, "GetWatchFeature",      GetWatchFeatureDef);
		LuaPushNamedCFunc(L, "SetWatchFeature",      SetWatchFeatureDef);
		LuaPushNamedCFunc(L, "GetWatchWeapon",       GetWatchWeaponDef);
		LuaPushNamedCFunc(L, "SetWatchWeapon",       SetWatchWeaponDef);
	lua_pop(L, 1);

	// add the custom file loader
	LuaPushNamedCFunc(L, "SendToUnsynced", SendToUnsynced);
	LuaPushNamedCFunc(L, "CallAsTeam",     CLuaHandleSynced::CallAsTeam);
	LuaPushNamedNumber(L, "COBSCALE",      COBSCALE);

	// load our libraries  (LuaSyncedCtrl overrides some LuaUnsyncedCtrl entries)
	if (
		!AddEntriesToTable(L, "VFS",         LuaVFS::PushSynced)           ||
		!AddEntriesToTable(L, "VFS",         LuaZipFileReader::PushSynced) ||
		!AddEntriesToTable(L, "VFS",         LuaZipFileWriter::PushSynced) ||
		!AddEntriesToTable(L, "UnitDefs",    LuaUnitDefs::PushEntries)     ||
		!AddEntriesToTable(L, "WeaponDefs",  LuaWeaponDefs::PushEntries)   ||
		!AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries)  ||
		!AddEntriesToTable(L, "Script",      LuaInterCall::PushEntriesSynced)   ||
		!AddEntriesToTable(L, "Spring",      LuaUnsyncedCtrl::PushEntries) ||
		!AddEntriesToTable(L, "Spring",      LuaSyncedCtrl::PushEntries)   ||
		!AddEntriesToTable(L, "Spring",      LuaSyncedRead::PushEntries)   ||
		!AddEntriesToTable(L, "Game",        LuaConstGame::PushEntries)    ||
		!AddEntriesToTable(L, "CMD",         LuaConstCMD::PushEntries)     ||
		!AddEntriesToTable(L, "CMDTYPE",     LuaConstCMDTYPE::PushEntries) ||
		!AddEntriesToTable(L, "COB",         LuaConstCOB::PushEntries)     ||
		!AddEntriesToTable(L, "SFX",         LuaConstSFX::PushEntries)     ||
		!AddEntriesToTable(L, "LOG",         LuaUtils::PushLogEntries)
	) {
		KillLua();
		return false;
	}

	// add code from the sub-class
	if (!base.AddSyncedCode(L)) {
		KillLua();
		return false;
	}

	lua_settop(L, 0);
	if (!LoadCode(L, code, file)) {
		KillLua();
		return false;
	}

	lua_settop(L, 0);
	eventHandler.AddClient(this);
	return true;
}
Ejemplo n.º 14
0
/*
 * Arguments: fd_udata, [options ...:
 *	reset (string: "reset"),
 *	baud_rate (number),
 *	character_size (string: "cs5".."cs8"),
 *	parity (string: "parno", "parodd", "pareven"),
 *	stop_bits (string: "sb1", "sb2"),
 *	flow_controls (string: "foff", "frtscts", "fxio")]
 * Returns: [fd_udata]
 */
static int
comm_init (lua_State *L)
{
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const int narg = lua_gettop(L);
  int i;

#ifndef _WIN32
  struct termios tio;

  if (tcgetattr(fd, &tio) == -1) goto err;
#else
  DCB dcb;

  dcb.DCBlength = sizeof(DCB);
  if (!GetCommState(fd, &dcb)) goto err;
#endif

  for (i = 2; i <= narg; ++i) {
#ifndef _WIN32
    tcflag_t mask = 0, flag = 0;
#endif

    if (lua_isnumber(L, i)) {
      const int baud_rate = lua_tointeger(L, i);
#ifndef _WIN32
      switch (baud_rate) {
      case 9600: flag = B9600; break;
      case 19200: flag = B19200; break;
      case 38400: flag = B38400; break;
      case 57600: flag = B57600; break;
      case 115200: flag = B115200; break;
      }
      if (cfsetispeed(&tio, flag) == -1
       || cfsetospeed(&tio, flag) == -1)
        goto err;
#else
      dcb.BaudRate = baud_rate;
#endif
    } else {
      const char *opt = lua_tostring(L, i);
      const char *endp = opt + lua_rawlen(L, i) - 1;

      if (!opt) continue;
      switch (*opt) {
      case 'r':  /* reset */
#ifndef _WIN32
        memset(&tio, 0, sizeof(struct termios));
#else
        memset(&dcb, 0, sizeof(DCB));
#endif
        continue;
      case 'c':  /* character size */
#ifndef _WIN32
        switch (*endp) {
        case '5': flag = CS5; break;
        case '6': flag = CS6; break;
        case '7': flag = CS7; break;
        default: flag = CS8;
        }
        mask = CSIZE;
#else
        dcb.ByteSize = (char) (*endp - '0');
#endif
        break;
      case 'p':  /* parity */
#ifndef _WIN32
        switch (*endp) {
        case 'd': flag = PARODD;
        case 'n': flag |= PARENB; break;
        default: flag = 0;  /* no parity */
        }
        mask = PARENB | PARODD;
#else
        {
          int parity;
          switch (*endp) {
          case 'd': parity = ODDPARITY; break;
          case 'n': parity = EVENPARITY; break;
          default: parity = 0;  /* no parity */
          }
          dcb.Parity = (char) parity;
          dcb.fParity = (parity != 0);
        }
#endif
        break;
      case 's':  /* stop bits */
#ifndef _WIN32
        if (*endp == '2') flag = CSTOPB;  /* else: one stop bit */
        mask = CSTOPB;
#else
        dcb.StopBits = (char) (*endp == '2' ? TWOSTOPBITS
         : ONESTOPBIT);
#endif
        break;
      case 'f':  /* flow controls */
        /* off */
#ifndef _WIN32
        mask = CRTSCTS;
        tio.c_iflag &= ~(IXON | IXOFF | IXANY);
#else
        dcb.fOutX = dcb.fInX = 0;
        dcb.fRtsControl = RTS_CONTROL_DISABLE;
        dcb.fOutxCtsFlow = 0;
#endif
        switch (opt[1]) {
        case 'x':  /* XON/XOFF */
#ifndef _WIN32
          tio.c_iflag |= (IXON | IXOFF | IXANY);
#else
          dcb.fOutX = dcb.fInX = 1;
#endif
          break;
        case 'r':  /* RTS/CTS */
#ifndef _WIN32
          flag = CRTSCTS;
#else
          dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
          dcb.fOutxCtsFlow = 1;
#endif
          break;
        }
        break;
      }
    }
#ifndef _WIN32
    tio.c_cflag &= ~mask;
    tio.c_cflag |= flag;
#endif
  }
#ifndef _WIN32
  tio.c_cflag |= CLOCAL | CREAD;

  if (!tcsetattr(fd, TCSANOW, &tio)) {
#else
  if (SetCommState(fd, &dcb)) {
#endif
    lua_settop(L, 1);
    return 1;
  }
 err:
  return sys_seterror(L, 0);
}

/*
 * Arguments: fd_udata, [controls (string: "dtr", "dsr", "rts", "cts") ...]
 * Returns: [fd_udata]
 */
static int
comm_control (lua_State *L)
{
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const int narg = lua_gettop(L);
  int i;

#ifndef _WIN32
  int flags;

  if (ioctl(fd, TIOCMGET, &flags) == -1) goto err;
  flags &= ~(TIOCM_DTR | TIOCM_DSR | TIOCM_RTS | TIOCM_CTS
   | TIOCM_ST | TIOCM_SR | TIOCM_CAR | TIOCM_RNG);
#else
  DCB dcb;

  dcb.DCBlength = sizeof(DCB);
  if (!GetCommState(fd, &dcb)) goto err;
  dcb.fDtrControl = dcb.fOutxDsrFlow
   = dcb.fRtsControl = dcb.fOutxCtsFlow = 0;
#endif

  for (i = 2; i <= narg; ++i) {
    const char *s = lua_tostring(L, i);

    if (!s) continue;
    switch (*s) {
    case 'd':  /* DTR/DSR */
#ifndef _WIN32
      flags |= (s[1] == 't') ? TIOCM_DTR : TIOCM_DSR;
#else
      if (s[1] == 't') dcb.fDtrControl = 1;
      else dcb.fOutxDsrFlow = 1;
#endif
      break;
    case 'r':  /* RTS */
#ifndef _WIN32
      flags |= TIOCM_RTS;
#else
      dcb.fRtsControl = 1;
#endif
      break;
    case 'c':  /* CTS */
#ifndef _WIN32
      flags |= TIOCM_CTS;
#else
      dcb.fOutxCtsFlow = 1;
#endif
      break;
    }
  }
#ifndef _WIN32
  if (!ioctl(fd, TIOCMSET, &flags)) {
#else
  if (SetCommState(fd, &dcb)) {
#endif
    lua_settop(L, 1);
    return 1;
  }
 err:
  return sys_seterror(L, 0);
}

/*
 * Arguments: fd_udata, [read_timeout (milliseconds)]
 * Returns: [fd_udata]
 */
static int
comm_timeout (lua_State *L)
{
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const int rtime = lua_tointeger(L, 2);

#ifndef _WIN32
  struct termios tio;

  if (tcgetattr(fd, &tio) == -1) goto err;
  tio.c_cc[VTIME] = rtime / 100;
  tio.c_cc[VMIN] = 0;

  if (!tcsetattr(fd, TCSANOW, &tio)) {
#else
  COMMTIMEOUTS timeouts;

  memset(&timeouts, 0, sizeof(COMMTIMEOUTS));
  timeouts.ReadIntervalTimeout = rtime ? (DWORD) rtime : MAXDWORD;
  timeouts.ReadTotalTimeoutMultiplier =
   timeouts.ReadTotalTimeoutConstant = rtime;

  if (SetCommTimeouts(fd, &timeouts)) {
#endif
    lua_settop(L, 1);
    return 1;
  }
#ifndef _WIN32
 err:
#endif
  return sys_seterror(L, 0);
}

/*
 * Arguments: fd_udata, in_buffer_size (number), out_buffer_size (number)
 * Returns: [fd_udata]
 */
static int
comm_queues (lua_State *L)
{
#ifndef _WIN32
  if (1) {
#else
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const int rqueue = lua_tointeger(L, 2);
  const int wqueue = lua_tointeger(L, 3);

  if (SetupComm(fd, rqueue, wqueue)) {
#endif
    lua_settop(L, 1);
    return 1;
  }
#ifdef _WIN32
  return sys_seterror(L, 0);
#endif
}

/*
 * Arguments: fd_udata, [mode (string: "rw", "r", "w")]
 * Returns: [fd_udata]
 */
static int
comm_purge (lua_State *L)
{
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const char *mode = lua_tostring(L, 2);
  int flags;

  flags = TCIOFLUSH;
  if (mode)
    switch (mode[0]) {
    case 'w': flags = TCOFLUSH; break;
    case 'r': if (!mode[1]) flags = TCIFLUSH;
    }
#ifndef _WIN32
  if (!tcflush(fd, flags)) {
#else
  if (PurgeComm(fd, flags)) {
#endif
    lua_settop(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}

/*
 * Arguments: fd_udata, options (string: "car", "cts", "dsr", "ring") ...
 * Returns: [boolean ...]
 */
static int
comm_wait (lua_State *L)
{
  const fd_t fd = (fd_t) lua_unboxinteger(L, 1, FD_TYPENAME);
  const int narg = lua_gettop(L);
  unsigned long status = 0;
  int flags = 0;
  int i, res;

  for (i = 2; i <= narg; ++i) {
    const char *s = lua_tostring(L, i);

    if (!s) continue;
    switch (*s) {
    case 'c':  /* CAR/CTS */
      flags |= (s[1] == 'a') ? TIOCM_CAR : TIOCM_CTS;
      break;
    case 'd':  /* DSR */
      flags |= TIOCM_DSR;
      break;
    case 'r':  /* RING */
      flags |= TIOCM_RNG;
      break;
    }
  }

  sys_vm_leave();
#ifndef _WIN32
  do {
#ifdef TIOCMIWAIT
    res = !(ioctl(fd, TIOCMIWAIT, flags) || ioctl(fd, TIOCMGET, &status));
#else
    while ((res = !ioctl(fd, TIOCMGET, &status)) && !(status & flags))
      usleep(10000);  /* 10 msec polling */
#endif
  } while (!res && sys_eintr());
#else
  res = SetCommMask(fd, flags) && WaitCommEvent(fd, &status, NULL);
#endif
  sys_vm_enter();

  if (res) {
    if (flags & TIOCM_CAR)
      lua_pushboolean(L, status & TIOCM_CAR);
    if (flags & TIOCM_CTS)
      lua_pushboolean(L, status & TIOCM_CTS);
    if (flags & TIOCM_DSR)
      lua_pushboolean(L, status & TIOCM_DSR);
    if (flags & TIOCM_RNG)
      lua_pushboolean(L, status & TIOCM_RNG);
    return narg - 1;
  }
  return sys_seterror(L, 0);
}
ngx_int_t
ngx_http_lua_header_filter_by_chunk(lua_State *L, ngx_http_request_t *r)
{
    int              old_exit_code = 0;
    ngx_int_t        rc;
    u_char          *err_msg;
    size_t           len;
#if (NGX_PCRE)
    ngx_pool_t      *old_pool;
#endif
    ngx_http_lua_ctx_t          *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
    if (ctx->exited) {
        old_exit_code = ctx->exit_code;
    }

    /*  initialize nginx context in Lua VM, code chunk at stack top    sp = 1 */
    ngx_http_lua_header_filter_by_lua_env(L, r);

#if (NGX_PCRE)
    /* XXX: work-around to nginx regex subsystem */
    old_pool = ngx_http_lua_pcre_malloc_init(r->pool);
#endif

    lua_pushcfunction(L, ngx_http_lua_traceback);
    lua_insert(L, 1);  /* put it under chunk and args */

    /*  protected call user code */
    rc = lua_pcall(L, 0, 1, 1);

    lua_remove(L, 1);  /* remove traceback function */

#if (NGX_PCRE)
    /* XXX: work-around to nginx regex subsystem */
    ngx_http_lua_pcre_malloc_done(old_pool);
#endif

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

    if (rc != 0) {
        /*  error occurred when running loaded code */
        err_msg = (u_char *) lua_tolstring(L, -1, &len);

        if (err_msg == NULL) {
            err_msg = (u_char *) "unknown reason";
            len = sizeof("unknown reason") - 1;
        }

        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                      "failed to run header_filter_by_lua*: %*s", len, err_msg);

        lua_settop(L, 0); /*  clear remaining elems on stack */

        return NGX_ERROR;
    }

    dd("exited: %d, exit code: %d, old exit code: %d",
       (int) ctx->exited, (int) ctx->exit_code, (int) old_exit_code);

#if 1
    /*  clear Lua stack */
    lua_settop(L, 0);
#endif

    if (ctx->exited && ctx->exit_code != old_exit_code) {
        if (ctx->exit_code == NGX_ERROR) {
            return NGX_ERROR;
        }

        dd("finalize request with %d", (int) ctx->exit_code);

        rc = ngx_http_filter_finalize_request(r, &ngx_http_lua_module,
                                              ctx->exit_code);
        if (rc == NGX_ERROR || rc == NGX_AGAIN) {
            return rc;
        }

        return NGX_DECLINED;
    }

    return NGX_OK;
}
Ejemplo n.º 16
0
int LuaStack::executeFunctionReturnArray(int handler,int numArgs,int numResults,__Array& resultArray)
{
    int top = lua_gettop(_state);
    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
            lua_settop(_state,top);
            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
            }
            lua_settop(_state,top);
            return 0;
        }
        
        // get return value,don't pass LUA_MULTRET to numResults,
        if (numResults <= 0)
        {
            lua_settop(_state,top);
            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,top);
    return 1;
}
Ejemplo n.º 17
0
static void lcurl_utils_pcall_close(lua_State *L, int obj){
  int top = lua_gettop(L);
  lua_pushvalue(L, obj);
  lcurl_util_pcall_method(L, "close", 0, 0, 0);
  lua_settop(L, top);
}
Ejemplo n.º 18
0
int ndisk_dir(Dictionary *dict, const NDiskEntry *entry, NDisk *disk, const wchar_t *path) {
    WIN32_FIND_DATAW fData;
    char *tmp = NULL, *sTmp = NULL;
    wchar_t *pTmp = NULL;
    unsigned long size = 0;
    int i = 0;
    SYSTEMTIME time;
    lua_reset();
    lua_getglobal(script, "entries");
    tmp = wtoc(entry->name);
    lua_getfield(script, -1, tmp);
    free(tmp);
    tmp = NULL;
    i = lua_gettop(script);
    if(lua_pcall(script, 0, 0, 0)) {
        OutputDebugStringA("Error Msg is: ");
        OutputDebugStringA(lua_tostring(script, -1));
    }
    lua_pop(script, 1);
    lua_getglobal(script, "dir");
    if(!lua_isfunction(script, -1)) {
        RequestProcW(PluginNumber, RT_MsgOK, L"ÅäÖôíÎó", L"ÍøÅ̽ű¾´íÎó, ²»ÄܶÁÈ¡µ±Ç°Ä¿Â¼µÄÄÚÈÝ. ", NULL, 0);
        return NDISK_FATAL;
    }
    if(ndisk_lua_push(script, disk) == NDISK_FATAL) {
        lua_settop(script, 0);
        return NDISK_FATAL;
    }
    tmp = wtoc(path);
    lua_pushstring(script, tmp);
    free(tmp);
    tmp = NULL;
    lua_setfield(script, -2, "path");
    if(lua_pcall(script, 1, 1, 0)) {
        OutputDebugStringA("Error Msg is: ");
        OutputDebugStringA(lua_tostring(script, -1));
    }

    if(lua_istable(script, -1)) {
        lua_pushnil(script);
        while (lua_next(script, -2)) {
            if(lua_istable(script, -1)) {
                memset(&fData, 0, sizeof(WIN32_FIND_DATAW));
                lua_pushnil(script);
                while(lua_next(script, -2)) {
                    tmp = (char *)lua_tostring(script, -2);
                    if(strcmp(tmp, "attribute") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        if(strcmp(sTmp, "file") == 0) {
                            fData.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
                        }
                        if(strcmp(sTmp, "directory") == 0) {
                            fData.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                        }
                    }
                    if(strcmp(tmp, "filename") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        wcslcpy(fData.cFileName, pTmp, PATH_MAX);
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "size") == 0) {
                        size = (unsigned long)lua_tonumber(script, -1);
                        fData.nFileSizeHigh = HIWORD(size);
                        fData.nFileSizeLow = LOWORD(size);
                    }
                    if(strcmp(tmp, "create") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftCreationTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "access") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftLastAccessTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "write") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftLastWriteTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    lua_pop(script, 1);
                }
                if(fData.cFileName) {
                    dict_set_element(dict, fData.cFileName, &fData, sizeof(WIN32_FIND_DATAW));
                }
            }
            lua_pop(script, 1);
        }
    }
    lua_pop(script, 1);
    return NDISK_OK;
}
Ejemplo n.º 19
0
int LTreeView::getOpennessState ( lua_State* ) {
    //bool alsoIncludeScrollPosition = LUA::getBoolean(2);
    // return LUA::TODO_RETURN_OBJECT_XmlElement( TreeView::getOpennessState( alsoIncludeScrollPosition ) );
    lua_settop(LUA::Get(), 1); // added by TODO
    return LUA::TODO_OBJECT( "XmlElement getOpennessState( alsoIncludeScrollPosition )" );
}
Ejemplo n.º 20
0
//lua 状态机的初始化
static int
_init(struct snlua *l, struct server_context *ctx, const char * args, size_t sz) {
	lua_State *L = l->L;
	l->ctx = ctx;
	lua_gc(L, LUA_GCSTOP, 0);//停止gc
	luaL_openlibs(L);//打开相关库

	//注册ctx到lua注册表
	lua_pushlightuserdata(L, ctx);
	lua_setfield(L, LUA_REGISTRYINDEX, "server_context");//lua_setfield:做一个等价于 t[k] = v 的操作, 这里 t 是给出的有效索引 index 处的值, 而 v 是栈顶的那个值

	//设置全局变量
	const char *path = optstring(ctx, "lua_path","./lualib/?.lua;./lualib/?/init.lua");
	lua_pushstring(L, path);
	lua_setglobal(L, "LUA_PATH");

	const char *cpath = optstring(ctx, "lua_cpath","./luaclib/?.so");
	lua_pushstring(L, cpath);
	lua_setglobal(L, "LUA_CPATH");

	const char *service = optstring(ctx, "luaservice", "./service/?.lua");
	lua_pushstring(L, service);
	lua_setglobal(L, "LUA_SERVICE");

	const char *preload = server_cmd_command(ctx, "GETENV", "preload");
	lua_pushstring(L, preload);
	lua_setglobal(L, "LUA_PRELOAD");

	lua_pushcfunction(L, traceback);
	assert(lua_gettop(L) == 1);

	//载入首个lua文件,生成chunk到栈顶
	const char * loader = optstring(ctx, "lualoader", "./lualib/loader.lua");
	int r = luaL_loadfile(L, loader);
	if (r != LUA_OK) {
		server_error(ctx, "Can't load %s : %s", loader, lua_tostring(L, -1));
		return 1;
	}
	lua_pushlstring(L, args, sz);
	/*
		lua_pcall(lua_State *L, int nargs, int nresults, int errfunc)
		nargs:传入参数个数
		nresults:需要返回参数个数
		errfunc:
			0 返回原始错误信息
				lua_errrun:运行时错误。
				lua_errmem:内存分配错误。对于此类错误,lua并不调用错误处理函数。
				lua_errerr:运行时错误处理函数误差。
			非0 即处理错误信息函数所在当前栈的位置,如上面执行了lua_pushcfunction(L, traceback);所以errfunc应该为1
	*/
	r = lua_pcall(L,1,0,1);//执行 loader.lua
	if (r != LUA_OK) {
		server_error(ctx, "lua loader error : %s", lua_tostring(L, -1));
		return 1;
	}

	//把栈上所有元素移除
	lua_settop(L,0);

	//重启gc
	lua_gc(L, LUA_GCRESTART, 0);

	return 0;
}
Ejemplo n.º 21
0
Archivo: file.c Proyecto: halfd/lem
/*
 * file:lock() method
 */
static void
file_lock_work(struct lem_async *a)
{
	struct file *f = (struct file *)a;
	struct flock fl = {
		.l_type = f->lock.type,
		.l_whence = SEEK_SET,
		.l_start = f->lock.start,
		.l_len = f->lock.len,
	};

	if (fcntl(f->fd, F_SETLK, &fl) == -1)
		f->ret = errno;
	else
		f->ret = 0;
}

static void
file_lock_reap(struct lem_async *a)
{
	struct file *f = (struct file *)a;
	lua_State *T = f->T;

	f->T = NULL;

	if (f->ret) {
		lem_queue(T, io_strerror(T, f->ret));
		return;
	}

	lua_pushboolean(T, 1);
	lem_queue(T, 1);
}

static int
file_lock(lua_State *T)
{
	static const short mode[] = { F_RDLCK, F_WRLCK, F_UNLCK };
	static const char *const modenames[] = { "r", "w", "u", NULL };
	struct file *f;
	int op;
	lua_Number start;
	lua_Number len;

	luaL_checktype(T, 1, LUA_TUSERDATA);
	op = luaL_checkoption(T, 2, NULL, modenames);
	start = luaL_optnumber(T, 3, 0);
	len = luaL_optnumber(T, 4, 0);
	f = lua_touserdata(T, 1);
	f->lock.start = (off_t)start;
	luaL_argcheck(T, (lua_Number)f->lock.start == start, 3,
			"not an integer in proper range");
	f->lock.len = (off_t)len;
	luaL_argcheck(T, (lua_Number)f->lock.len == len, 4,
			"not an integer in proper range");
	if (f->fd < 0)
		return io_closed(T);
	if (f->T != NULL)
		return io_busy(T);

	f->T = T;
	f->lock.type = mode[op];
	lem_async_do(&f->a, file_lock_work, file_lock_reap);

	lua_settop(T, 1);
	return lua_yield(T, 1);
}
Ejemplo n.º 22
0
static int vlclua_add_callback( lua_State *L )
{
    vlclua_callback_t *p_callback;
    static int i_index = 0;
    vlc_object_t **pp_obj = luaL_checkudata( L, 1, "vlc_object" );
    const char *psz_var = luaL_checkstring( L, 2 );
    lua_settop( L, 4 ); /* makes sure that optional data arg is set */
    if( !lua_isfunction( L, 3 ) )
        return vlclua_error( L );
    i_index++;

    p_callback = (vlclua_callback_t*)malloc( sizeof( vlclua_callback_t ) );
    if( !p_callback )
        return vlclua_error( L );

    /* obj var func data */
    lua_getglobal( L, "vlc" );
    /* obj var func data vlc */
    lua_getfield( L, -1, "callbacks" );
    if( lua_isnil( L, -1 ) )
    {
        lua_pop( L, 1 );
        lua_newtable( L );
        lua_setfield( L, -2, "callbacks" );
        lua_getfield( L, -1, "callbacks" );
    }
    /* obj var func data vlc callbacks */
    lua_remove( L, -2 );
    /* obj var func data callbacks */
    lua_pushinteger( L, i_index );
    /* obj var func data callbacks index */
    lua_insert( L, -4 );
    /* obj var index func data callbacks */
    lua_insert( L, -4 );
    /* obj var callbacks index func data */
    lua_createtable( L, 0, 0 );
    /* obj var callbacks index func data cbtable */
    lua_insert( L, -2 );
    /* obj var callbacks index func cbtable data */
    lua_setfield( L, -2, "data" );
    /* obj var callbacks index func cbtable */
    lua_insert( L, -2 );
    /* obj var callbacks index cbtable func */
    lua_setfield( L, -2, "callback" );
    /* obj var callbacks index cbtable */
    lua_pushlightuserdata( L, *pp_obj ); /* will be needed in vlclua_del_callback */
    /* obj var callbacks index cbtable p_obj */
    lua_setfield( L, -2, "private1" );
    /* obj var callbacks index cbtable */
    lua_pushvalue( L, 2 ); /* will be needed in vlclua_del_callback */
    /* obj var callbacks index cbtable var */
    lua_setfield( L, -2, "private2" );
    /* obj var callbacks index cbtable */
    lua_pushlightuserdata( L, p_callback ); /* will be needed in vlclua_del_callback */
    /* obj var callbacks index cbtable p_callback */
    lua_setfield( L, -2, "private3" );
    /* obj var callbacks index cbtable */
    lua_settable( L, -3 );
    /* obj var callbacks */
    lua_pop( L, 3 );
    /* <empty stack> */

    /* Do not move this before the lua specific code (it somehow changes
     * the function in the stack to nil) */
    p_callback->i_index = i_index;
    p_callback->i_type = var_Type( *pp_obj, psz_var );
    p_callback->L = lua_newthread( L ); /* Do we have to keep a reference to this thread somewhere to prevent garbage collection? */

    var_AddCallback( *pp_obj, psz_var, vlclua_callback, p_callback );
    return 0;
}
Ejemplo n.º 23
0
/*
 * Push a proxy userdata on the stack.
 * returns NULL if ok, else some error string related to bad idfunc behavior or module require problem
 * (error cannot happen with mode_ == eLM_ToKeeper)
 *
 * Initializes necessary structures if it's the first time 'idfunc' is being
 * used in this Lua state (metatable, registring it). Otherwise, increments the
 * reference count.
 */
char const* push_deep_proxy( struct s_Universe* U, lua_State* L, DEEP_PRELUDE* prelude, enum eLookupMode mode_)
{
	DEEP_PRELUDE** proxy;

	// Check if a proxy already exists
	push_registry_subtable_mode( L, DEEP_PROXY_CACHE_KEY, "v");                                        // DPC
	lua_pushlightuserdata( L, prelude->deep);                                                          // DPC deep
	lua_rawget( L, -2);                                                                                // DPC proxy
	if ( !lua_isnil( L, -1))
	{
		lua_remove( L, -2);                                                                              // proxy
		return NULL;
	}
	else
	{
		lua_pop( L, 1);                                                                                  // DPC
	}

	MUTEX_LOCK( &U->deep_lock);
	++ (prelude->refcount);  // one more proxy pointing to this deep data
	MUTEX_UNLOCK( &U->deep_lock);

	STACK_GROW( L, 7);
	STACK_CHECK( L);

	proxy = lua_newuserdata( L, sizeof( DEEP_PRELUDE*));                                               // DPC proxy
	ASSERT_L( proxy);
	*proxy = prelude;

	// Get/create metatable for 'idfunc' (in this state)
	lua_pushlightuserdata( L, prelude->idfunc);                                                        // DPC proxy idfunc
	get_deep_lookup( L);                                                                               // DPC proxy metatable?

	if( lua_isnil( L, -1)) // // No metatable yet.
	{
		char const* modname;
		int oldtop = lua_gettop( L);                                                                     // DPC proxy nil
		lua_pop( L, 1);                                                                                  // DPC proxy
		// 1 - make one and register it
		if( mode_ != eLM_ToKeeper)
		{
			prelude->idfunc( L, eDO_metatable);                                                            // DPC proxy metatable deepversion
			if( lua_gettop( L) - oldtop != 1 || !lua_istable( L, -2) || !lua_isstring( L, -1))
			{
				lua_settop( L, oldtop);                                                                      // DPC proxy X
				lua_pop( L, 3);                                                                              //
				return "Bad idfunc(eOP_metatable): unexpected pushed value";
			}
			luaG_pushdeepversion( L);                                                                      // DPC proxy metatable deepversion deepversion
			if( !lua501_equal( L, -1, -2))
			{
				lua_pop( L, 5);                                                                              //
				return "Bad idfunc(eOP_metatable): mismatched deep version";
			}
			lua_pop( L, 2);                                                                                // DPC proxy metatable
			// make sure the idfunc didn't export __gc, as we will store our own
			lua_getfield( L, -1, "__gc");                                                                  // DPC proxy metatable __gc
			if( !lua_isnil( L, -1))
			{
				lua_pop( L, 4);                                                                              //
				return "idfunc-created metatable shouldn't contain __gc";
			}
			lua_pop( L, 1);                                                                                // DPC proxy metatable
		}
		else
		{
			// keepers need a minimal metatable that only contains __gc
			lua_newtable( L);                                                                              // DPC proxy metatable
		}
		// Add our own '__gc' method
		lua_pushcfunction( L, deep_userdata_gc);                                                         // DPC proxy metatable __gc
		lua_setfield( L, -2, "__gc");                                                                    // DPC proxy metatable

		// Memorize for later rounds
		lua_pushvalue( L, -1);                                                                           // DPC proxy metatable metatable
		lua_pushlightuserdata( L, prelude->idfunc);                                                      // DPC proxy metatable metatable idfunc
		set_deep_lookup( L);                                                                             // DPC proxy metatable

		// 2 - cause the target state to require the module that exported the idfunc
		// this is needed because we must make sure the shared library is still loaded as long as we hold a pointer on the idfunc
		{
			int oldtop = lua_gettop( L);
			modname = (char const*) prelude->idfunc( L, eDO_module);                                       // DPC proxy metatable
			// make sure the function pushed nothing on the stack!
			if( lua_gettop( L) - oldtop != 0)
			{
				lua_pop( L, 3);                                                                              //
				return "Bad idfunc(eOP_module): should not push anything";
			}
		}
		if( modname) // we actually got a module name
		{
			// somehow, L.registry._LOADED can exist without having registered the 'package' library.
			lua_getglobal( L, "require");                                                                  // DPC proxy metatable require()
			// check that the module is already loaded (or being loaded, we are happy either way)
			if( lua_isfunction( L, -1))
			{
				lua_pushstring( L, modname);                                                                 // DPC proxy metatable require() "module"
				lua_getfield( L, LUA_REGISTRYINDEX, "_LOADED");                                              // DPC proxy metatable require() "module" _R._LOADED
				if( lua_istable( L, -1))
				{
					bool_t alreadyloaded;
					lua_pushvalue( L, -2);                                                                     // DPC proxy metatable require() "module" _R._LOADED "module"
					lua_rawget( L, -2);                                                                        // DPC proxy metatable require() "module" _R._LOADED module
					alreadyloaded = lua_toboolean( L, -1);
					if( !alreadyloaded) // not loaded
					{
						int require_result;
						lua_pop( L, 2);                                                                          // DPC proxy metatable require() "module"
						// require "modname"
						require_result = lua_pcall( L, 1, 0, 0);                                                 // DPC proxy metatable error?
						if( require_result != LUA_OK)
						{
							// failed, return the error message
							lua_pushfstring( L, "error while requiring '%s' identified by idfunc(eOP_module): ", modname);
							lua_insert( L, -2);                                                                    // DPC proxy metatable prefix error
							lua_concat( L, 2);                                                                     // DPC proxy metatable error
							return lua_tostring( L, -1);
						}
					}
					else // already loaded, we are happy
					{
						lua_pop( L, 4);                                                                          // DPC proxy metatable
					}
				}
				else // no L.registry._LOADED; can this ever happen?
				{
					lua_pop( L, 6);                                                                            //
					return "unexpected error while requiring a module identified by idfunc(eOP_module)";
				}
			}
			else // a module name, but no require() function :-(
			{
				lua_pop( L, 4);                                                                              //
				return "lanes receiving deep userdata should register the 'package' library";
			}
		}
	}
	STACK_MID( L, 2);                                                                                  // DPC proxy metatable
	ASSERT_L( lua_isuserdata( L, -2));
	ASSERT_L( lua_istable( L, -1));
	lua_setmetatable( L, -2);                                                                          // DPC proxy

	// If we're here, we obviously had to create a new proxy, so cache it.
	lua_pushlightuserdata( L, (*proxy)->deep);                                                         // DPC proxy deep
	lua_pushvalue( L, -2);                                                                             // DPC proxy deep proxy
	lua_rawset( L, -4);                                                                                // DPC proxy
	lua_remove( L, -2);                                                                                // proxy
	ASSERT_L( lua_isuserdata( L, -1));
	STACK_END( L, 0);
	return NULL;
}
Ejemplo n.º 24
0
static int vlclua_del_callback( lua_State *L )
{
    vlclua_callback_t *p_callback;
    bool b_found = false;
    vlc_object_t **pp_obj = luaL_checkudata( L, 1, "vlc_object" );
    const char *psz_var = luaL_checkstring( L, 2 );
    lua_settop( L, 4 ); /* makes sure that optional data arg is set */
    if( !lua_isfunction( L, 3 ) )
        return vlclua_error( L );

    /* obj var func data */
    lua_getglobal( L, "vlc" );
    /* obj var func data vlc */
    lua_getfield( L, -1, "callbacks" );
    if( lua_isnil( L, -1 ) )
        return luaL_error( L, "Couldn't find matching callback." );
    /* obj var func data vlc callbacks */
    lua_remove( L, -2 );
    /* obj var func data callbacks */
    lua_pushnil( L );
    /* obj var func data callbacks index */
    while( lua_next( L, -2 ) )
    {
        /* obj var func data callbacks index value */
        if( lua_isnumber( L, -2 ) )
        {
            lua_getfield( L, -1, "private2" );
            /* obj var func data callbacks index value private2 */
            if( lua_equal( L, 2, -1 ) ) /* var name is equal */
            {
                lua_pop( L, 1 );
                /* obj var func data callbacks index value */
                lua_getfield( L, -1, "callback" );
                /* obj var func data callbacks index value callback */
                if( lua_equal( L, 3, -1 ) ) /* callback function is equal */
                {
                    lua_pop( L, 1 );
                    /* obj var func data callbacks index value */
                    lua_getfield( L, -1, "data" ); /* callback data is equal */
                    /* obj var func data callbacks index value data */
                    if( lua_equal( L, 4, -1 ) )
                    {
                        vlc_object_t *p_obj2;
                        lua_pop( L, 1 );
                        /* obj var func data callbacks index value */
                        lua_getfield( L, -1, "private1" );
                        /* obj var func data callbacks index value private1 */
                        p_obj2 = (vlc_object_t*)luaL_checklightuserdata( L, -1 );
                        if( p_obj2 == *pp_obj ) /* object is equal */
                        {
                            lua_pop( L, 1 );
                            /* obj var func data callbacks index value */
                            lua_getfield( L, -1, "private3" );
                            /* obj var func data callbacks index value private3 */
                            p_callback = (vlclua_callback_t*)luaL_checklightuserdata( L, -1 );
                            lua_pop( L, 2 );
                            /* obj var func data callbacks index */
                            b_found = true;
                            break;
                        }
                        else
                        {
                            /* obj var func data callbacks index value private1 */
                            lua_pop( L, 1 );
                            /* obj var func data callbacks index value */
                        }
                    }
                    else
                    {
                        /* obj var func data callbacks index value data */
                        lua_pop( L, 1 );
                        /* obj var func data callbacks index value */
                    }
                }
                else
                {
                    /* obj var func data callbacks index value callback */
                    lua_pop( L, 1 );
                    /* obj var func data callbacks index value */
                }
            }
            else
            {
                /* obj var func data callbacks index value private2 */
                lua_pop( L, 1 );
                /* obj var func data callbacks index value */
            }
        }
        /* obj var func data callbacks index value */
        lua_pop( L, 1 );
        /* obj var func data callbacks index */
    }
    if( b_found == false )
        /* obj var func data callbacks */
        return luaL_error( L, "Couldn't find matching callback." );
    /* else */
        /* obj var func data callbacks index*/

    var_DelCallback( *pp_obj, psz_var, vlclua_callback, p_callback );
    free( p_callback );

    /* obj var func data callbacks index */
    lua_pushnil( L );
    /* obj var func data callbacks index nil */
    lua_settable( L, -3 ); /* delete the callback table entry */
    /* obj var func data callbacks */
    lua_pop( L, 5 );
    /* <empty stack> */
    return 0;
}
Ejemplo n.º 25
0
/**
 * Initialize the library, returns a table.  This function is called by Lua
 * when this library is dynamically loaded.  Note that the table is also stored
 * as the global "gnome" (by the "require" command), and that is accessed
 * from this library sometimes.
 *
 * @luaparam name  This library's name, i.e. "gnome".
 */
int luaopen_gnome(lua_State *L)
{
    // get this module's name, then discard the argument.
    lib_name = strdup(lua_tostring(L, 1));
    lg_dl_init(L, &gnome_dynlink);
    lua_settop(L, 0);
    lg_debug_flags_global(L);

    g_type_init();

    /* make the table to return, and make it global as "gnome" */
    luaL_register(L, lib_name, gnome_methods);
    _init_module_info(L);
    lg_init_object(L);
    lg_init_debug(L);
    lg_init_boxed(L);
    lg_init_closure(L);

    // an object that can be used as NIL
    lua_pushliteral(L, "NIL");
    lua_pushlightuserdata(L, NULL);
    lua_rawset(L, -3);

    // a metatable to make another table have weak values
    lua_newtable(L);			// gnome mt
    lua_pushliteral(L, "v");		// gnome mt "v"
    lua_setfield(L, -2, "__mode");	// gnome mt

    // Table with all object metatables; [name] = table.  When no objects
    // of the given type exist anymore, they may be removed if weak values
    // are used; this doesn't make much sense, as a program will most likely
    // use a certain object type again if it is used once.
    lua_newtable(L);			// gnome mt t
    lua_setfield(L, 1, LUAGNOME_METATABLES);	// gnome mt
    
    // objects: not a weak table.  It only contains references to entries
    // in the aliases table; they are removed manually when the last alias
    // is garbage collected.
    lua_newtable(L);			    // gnome mt t
    lua_setfield(L, 1, LUAGNOME_WIDGETS);    // gnome mt

    // gnome.aliases.  It has automatic garbage collection (weak values).
    lua_newtable(L);
    lua_pushvalue(L, -2);
    lua_setmetatable(L, -2);
    lua_setfield(L, 1, LUAGNOME_ALIASES);    // gnome mt

    // gnome.typemap is a table that maps hash values of native types to
    // their typespec_t.  It is required in lg_type_normalize.
    lua_newtable(L);
    lua_setfield(L, 1, "typemap");

    // gnome.fundamental_map is a table that maps hash values of fundamental
    // types to their index in ffi_type_map.
    lg_create_fundamental_map(L);

    lua_pop(L, 1);			    // gnome


    /* default attribute table of an object */
    lua_newtable(L);			    // gnome t
    lua_setfield(L, 1, LUAGNOME_EMPTYATTR);

    /* execute the glue library (compiled in) */
    // XXX this should be moved to the modules
    // luaL_loadbuffer(L, override_data, override_size, "override.lua");
    // lua_pcall(L, 0, 0, 0);

    // make gnome its own metatable - it contains __index and maybe other
    // special methods.
    lua_pushvalue(L, -1);
    lua_setmetatable(L, -2);

    // Add the API
    lua_pushlightuserdata(L, &module_api);
    lua_setfield(L, 1, "api");

    // Can't initialize Gtk right away: if memory tracing is used, it must
    // be activated first; otherwise, initial allocations are not noted and
    // lead to errors later on, e.g. when a block is reallocated.
    // gtk_init(NULL, NULL);

    // set up error logging to be more useful: display which function is
    // currently running before showing the error message.
    g_log_set_default_handler(lg_log_func, NULL);

    /* one retval on the stack: gnome.  This is usually not used anywhere,
     * but you have to use the global variable "gnome". */
    return 1;
}
Ejemplo n.º 26
0
ContactModel::ContactModel(QObject *parent) :
    FilteringModel(parent),
    mDefaultAvatar("emojis/iphone-emoji/WRENCH.png")
{
    int error = luaL_loadstring(L, "contacts = require('contacts')") || lua_pcall(L, 0, 0, 0);
    if (error) {
        qDebug() << "Error loading contacts: " << QString::fromUtf8(lua_tolstring(L, -1, NULL));
        return;
    }

    lua_getglobal(L, "contacts");

#ifdef Q_OS_WIN32
    QString homePath = QProcessEnvironment::systemEnvironment().value("USERPROFILE");
#else
    QString homePath = QProcessEnvironment::systemEnvironment().value("HOME");
#endif

    QDir homeDir = QDir(homePath);
    QString vcf = homeDir.absoluteFilePath(".android/contacts.vcf");
    QFile vcfFile(vcf);
    if (!vcfFile.exists()) {
        if (QFile("contacts.vcf").exists()) {
            vcf = "contacts.vcf";
        } else {
            vcf = "test.vcf";
        }
    }

    lua_getfield(L, -1, "read_vcf");
    lua_pushstring(L, qPrintable(vcf));

    error = lua_pcall(L, 1, 1, 0);
    if (error) {
        qDebug() << "Error: can't read vcf file: " << vcf;
        return;
    }

    int n = luaL_len(L, -1);
    for (int i = 1; i <= n; i++) {
        VCard vcard;
        lua_rawgeti(L, -1, i);

        lua_getfield(L, -1, "FNWrench");
        vcard.mName = (QString::fromUtf8(lua_tolstring(L, -1, NULL)));
        lua_settop(L, -2);

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

        int nTel = luaL_len(L, -1);
        for (int iTel = 1; iTel <= nTel; iTel++) {
            lua_rawgeti(L, -1, iTel);
            vcard.mTels.push_back(QString::fromUtf8(lua_tolstring(L, -1, NULL)));
            lua_settop(L, -2);
        }
        lua_settop(L, -2);

        lua_getfield(L, -1, "EMAILS");
        int nEmail = luaL_len(L, -1);
        for (int iEmail = 1; iEmail <= nEmail; iEmail++) {
            lua_rawgeti(L, -1, iEmail);
            vcard.mEmails.push_back(QString::fromUtf8(lua_tolstring(L, -1, NULL)));
            lua_settop(L, -2);
        }
        lua_settop(L, -2);

        lua_getfield(L, -1, "photo_data");
        size_t len = 0;
        const char* photo_data = lua_tolstring(L, -1, &len);
        if (photo_data != NULL && len != 0) {
            QByteArray photoBytes(photo_data, len);

            photoBytes = QByteArray::fromBase64(photoBytes);
            if (!vcard.mAvatar.loadFromData(photoBytes)) {
                qDebug() << "load for " << vcard.mName << " has failed";
            } else {
                vcard.mAvatar = vcard.mAvatar.scaled(48, 48);
            }
            if (vcard.mAvatar.isNull()) {
                qDebug() << "my icon is null";
            }
        } else {
            vcard.mAvatar = mDefaultAvatar;
        }
        lua_settop(L, -2);

        lua_settop(L, -2);

        mVcards << vcard;
    }

    lua_settop(L, 0);
    foreach(const VCard& vcard, mVcards) {
        vcard.mPinyin = getPinyinSpelling(vcard.mName);
    }
Ejemplo n.º 27
0
void lua_engine::close()
{
	lua_settop(m_lua_state, 0);  /* clear stack */
	lua_close(m_lua_state);
}
Ejemplo n.º 28
0
bool CKeyAutoBinder::BindBuildType(const string& keystr,
                                   const vector<string>& requirements,
                                   const vector<string>& sortCriteria,
                                   const vector<string>& chords)
{
	if (L == NULL) {
		return false;
	}

	lua_settop(L, 0);

	const string reqCall = MakeRequirementCall(requirements);
	const string sortCall = MakeSortCriteriaCall(sortCriteria);

	if (keyBindings->GetDebug() > 1) {
		logOutput.Print("--reqCall(%s):\n", keystr.c_str());
		logOutput.Print(reqCall);
		logOutput.Print("--sortCall(%s):\n", keystr.c_str());
		logOutput.Print(sortCall);
	}

	if (!LoadCode(reqCall,  keystr + ":HasReqs()") ||
	    !LoadCode(sortCall, keystr + ":IsBetter()")) {
		return false;
	}

	vector<UnitDefHolder> defs;

	const std::map<std::string, int>& udMap = unitDefHandler->unitID;
	std::map<std::string, int>::const_iterator udIt;
	for (udIt = udMap.begin(); udIt != udMap.end(); udIt++) {
	  const UnitDef* ud = unitDefHandler->GetUnitByID(udIt->second);
		if (ud == NULL) {
	  	continue;
		}
		if (HasRequirements(L, ud->id)) {
			UnitDefHolder udh;
			udh.ud = ud;
			udh.udID = ud->id;
			defs.push_back(udh);
		}
	}

	// sort the results
	tmpLuaState = L;
	thisBinder = this;
	sort(defs.begin(), defs.end());

	// add the bindings
	for (unsigned int i = 0; i < defs.size(); i++) {
		const string bindStr = "bind";
		const string lowerName = StringToLower(defs[i].ud->name);
		const string action = string("buildunit_") + lowerName;
		keyBindings->Command(bindStr + " " + keystr + " " + action);
		if ((i < chords.size()) && (StringToLower(chords[i]) != "none")) {
			keyBindings->Command(bindStr + " " + chords[i] + " " + action);
		}
		if (keyBindings->GetDebug() > 0) {
			string msg = "auto-";
			msg += bindStr + " " + keystr + " " + action;
			logOutput.Print(msg);
		}
	}

	return true;
}
Ejemplo n.º 29
0
Archivo: luv.c Proyecto: Udo/npasync
LUALIB_API int luaopen_luv(lua_State *L) {

#ifndef WIN32
  signal(SIGPIPE, SIG_IGN);
#endif

  int i;
  uv_loop_t*    loop;
  luv_state_t*  curr;
  luv_object_t* stdfh;

  lua_settop(L, 0);

  /* register decoders */
  lua_pushcfunction(L, luvL_lib_decoder);
  lua_setfield(L, LUA_REGISTRYINDEX, "luv:lib:decoder");

#ifdef USE_ZMQ
  lua_pushcfunction(L, luvL_zmq_ctx_decoder);
  lua_setfield(L, LUA_REGISTRYINDEX, "luv:zmq:decoder");
#endif

  /* luv */
  luvL_new_module(L, "luv", luv_funcs);

  /* luv.thread */
  luvL_new_module(L, "luv_thread", luv_thread_funcs);
  lua_setfield(L, -2, "thread");
  luvL_new_class(L, LUV_THREAD_T, luv_thread_meths);
  lua_pop(L, 1);

  if (!MAIN_INITIALIZED) {
    luvL_thread_init_main(L);
    lua_pop(L, 1);
  }

  /* luv.fiber */
  luvL_new_module(L, "luv_fiber", luv_fiber_funcs);

  /* borrow coroutine.yield (fast on LJ2) */
  lua_getglobal(L, "coroutine");
  lua_getfield(L, -1, "yield");
  lua_setfield(L, -3, "yield");
  lua_pop(L, 1); /* coroutine */

  lua_setfield(L, -2, "fiber");

  luvL_new_class(L, LUV_FIBER_T, luv_fiber_meths);
  lua_pop(L, 1);

  /* luv.codec */
  luvL_new_module(L, "luv_codec", luv_codec_funcs);
  lua_setfield(L, -2, "codec");

  /* luv.timer */
  luvL_new_module(L, "luv_timer", luv_timer_funcs);
  lua_setfield(L, -2, "timer");
  luvL_new_class(L, LUV_TIMER_T, luv_timer_meths);
  lua_pop(L, 1);

  /* luv.idle */
  luvL_new_module(L, "luv_idle", luv_idle_funcs);
  lua_setfield(L, -2, "idle");
  luvL_new_class(L, LUV_IDLE_T, luv_idle_meths);
  lua_pop(L, 1);

  /* luv.fs */
  luvL_new_module(L, "luv_fs", luv_fs_funcs);
  lua_setfield(L, -2, "fs");
  luvL_new_class(L, LUV_FILE_T, luv_file_meths);
  lua_pop(L, 1);

  /* luv.pipe */
  luvL_new_module(L, "luv_pipe", luv_pipe_funcs);
  lua_setfield(L, -2, "pipe");
  luvL_new_class(L, LUV_PIPE_T, luv_stream_meths);
  //luaL_register(L, NULL, luv_pipe_meths);
	luaL_setfuncs(L, luv_pipe_meths, 0);
  lua_pop(L, 1);

  /* luv.std{in,out,err} */
  if (!MAIN_INITIALIZED) {
    MAIN_INITIALIZED = 1;
    loop = luvL_event_loop(L);
    curr = luvL_state_self(L);

    const char* stdfhs[] = { "stdin", "stdout", "stderr" };
    for (i = 0; i < 3; i++) {
#ifdef WIN32
      const uv_file fh = GetStdHandle(i == 0 ? STD_INPUT_HANDLE
       : (i == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE));
#else
      const uv_file fh = i;
#endif
      stdfh = (luv_object_t*)lua_newuserdata(L, sizeof(luv_object_t));
      luaL_getmetatable(L, LUV_PIPE_T);
      lua_setmetatable(L, -2);
      luvL_object_init(curr, stdfh);
      uv_pipe_init(loop, &stdfh->h.pipe, 0);
      uv_pipe_open(&stdfh->h.pipe, fh);
      lua_pushvalue(L, -1);
      lua_setfield(L, LUA_REGISTRYINDEX, stdfhs[i]);
      lua_setfield(L, -2, stdfhs[i]);
    }
  }

  /* luv.net */
  luvL_new_module(L, "luv_net", luv_net_funcs);
  lua_setfield(L, -2, "net");
  luvL_new_class(L, LUV_NET_TCP_T, luv_stream_meths);
  //luaL_register(L, NULL, luv_net_tcp_meths);
	luaL_setfuncs(L, luv_net_tcp_meths, 0);
  lua_pop(L, 1);

  /* luv.process */
  luvL_new_module(L, "luv_process", luv_process_funcs);
  lua_setfield(L, -2, "process");
  luvL_new_class(L, LUV_PROCESS_T, luv_process_meths);
  lua_pop(L, 1);

  /* luv.zmq */
#ifdef USE_ZMQ
  luvL_new_module(L, "luv_zmq", luv_zmq_funcs);
  const luv_const_reg_t* c = luv_zmq_consts;
  for (; c->key; c++) {
    lua_pushinteger(L, c->val);
    lua_setfield(L, -2, c->key);
  }
  lua_setfield(L, -2, "zmq");
  luvL_new_class(L, LUV_ZMQ_CTX_T, luv_zmq_ctx_meths);
  luvL_new_class(L, LUV_ZMQ_SOCKET_T, luv_zmq_socket_meths);
  lua_pop(L, 2);
#endif

  lua_settop(L, 1);
  return 1;
}
Ejemplo n.º 30
0
 virtual void TearDown()
 {
     lua_settop(L, 0);
     lua_close(L);
 }