From 7f973d7fe8b1d7a8c991b52bc7e2422fb9b39a7c Mon Sep 17 00:00:00 2001 From: Allanis Date: Thu, 4 Apr 2013 21:24:25 +0100 Subject: [PATCH] [Add] Improved space.getPlanet() mission lua. --- src/misn_lua.c | 37 ++++++++++++++++++++++--------------- src/space.c | 28 ++++++++++++++++++++++++++++ src/space.h | 1 + 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/src/misn_lua.c b/src/misn_lua.c index 7bf06b9..2f5b894 100644 --- a/src/misn_lua.c +++ b/src/misn_lua.c @@ -209,24 +209,31 @@ static int space_getPlanet(lua_State* L) { if(lua_gettop(L) == 0) { // Get random planet. + lua_pushstring(L, space_getRndPlanet()); + return 1; } - else if(lua_istable(L, -1)) { - // Get planet of faction in table. - - // Load up the table. - lua_pushnil(L); - nfactions = (int) lua_gettop(L); - factions = malloc(sizeof(int) * nfactions); - i = 0; - while(lua_next(L, -2) != 0) { - factions[i++] = (int) lua_tonumber(L, -1); - lua_pop(L, 1); + else if(lua_isnumber(L, -1) || lua_istable(L, -1)) { + // Faction table or single. + if(lua_isnumber(L, -1)) { + // Faction is just a number. + i = lua_tonumber(L, -1); + planets = space_getFactionPlanet(&nplanets, &i, 1); } + else if(lua_istable(L, -1)) { + // Load up the table. + lua_pushnil(L); + nfactions = (int) lua_gettop(L); + factions = malloc(sizeof(int) * nfactions); + i = 0; + while(lua_next(L, -2) != 0) { + factions[i++] = (int) lua_tonumber(L, -1); + lua_pop(L, 1); + } - // Get the planets. - planets = space_getFactionPlanet(&nplanets, factions, nfactions); - free(factions); - + // Get the planets. + planets = space_getFactionPlanet(&nplanets, factions, nfactions); + free(factions); + } // Choose random planet. if(nplanets == 0) { // No suitable planets. diff --git a/src/space.c b/src/space.c index e7f947d..69ac1b0 100644 --- a/src/space.c +++ b/src/space.c @@ -226,6 +226,34 @@ char** space_getFactionPlanet(int* nplanets, int* factions, int nfactions) { return tmp; } +// Return the name of a random planet. +char* space_getRndPlanet(void) { + int i, j; + char** tmp; + int ntmp; + int mtmp; + char* res; + + ntmp = 0; + mtmp = 25; + tmp = malloc(sizeof(char)*mtmp); + + for(i = 0; i < systems_nstack; i++) + for(j = 0; j < systems_stack[i].nplanets; j++) { + ntmp++; + if(ntmp > mtmp) { + mtmp += 25; + tmp = realloc(tmp, sizeof(char*) * mtmp); + } + tmp[ntmp-1] = systems_stack[i].planets[j].name; + } + + res = tmp[RNG(0, ntmp-1)]; + free(tmp); + + return res; +} + // Basically used for spawning fleets. void space_update(const double dt) { unsigned int t; diff --git a/src/space.h b/src/space.h index eb7c38b..4d340da 100644 --- a/src/space.h +++ b/src/space.h @@ -109,5 +109,6 @@ void space_update(const double dt); int space_canHyperspace(Pilot* p); int space_hyperspace(Pilot* p); char** space_getFactionPlanet(int* nplanets, int* factions, int nfactions); +char* space_getRndPlanet(void); extern char* stardate;