/** * @brief Initializes the news. * * @return 0 on success. */ int news_init (void) { lua_State *L; char *buf; uint32_t bufsize; /* Already initialized. */ if (news_state != NULL) return 0; /* Create the state. */ news_state = nlua_newState(); L = news_state; /* Load the libraries. */ nlua_loadBasic(L); nlua_load(L,luaopen_string); nlua_loadStandard(L, 1); /* Load the news file. */ buf = ndata_read( LUA_NEWS, &bufsize ); if (luaL_dobuffer(news_state, buf, bufsize, LUA_NEWS) != 0) { WARN("Failed to load news file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", LUA_NEWS, lua_tostring(L,-1)); return -1; } free(buf); return 0; }
JNIEXPORT long JNICALL Java_com_torchandroid_facedemo_CameraClass_initTorch(JNIEnv *env, jobject thiz, jobject assetManager) { // get native asset manager. This allows access to files stored in the assets folder AAssetManager* manager = AAssetManager_fromJava(env, assetManager); assert( NULL != manager); lua_State *L = NULL; L = inittorch(manager); // create a lua_State // load and run file char file[] = "main.lua"; int ret; long size = android_asset_get_size(file); if (size != -1) { char *filebytes = android_asset_get_bytes(file); ret = luaL_dobuffer(L, filebytes, size, "main"); if (ret == 1) { D("Torch Error doing resource: %s\n", file); D(lua_tostring(L,-1)); } else { D("Torch script ran succesfully."); } } lua_register(L,"parse",parse); //This function is used by main.lua. return (long) L; }
JNIEXPORT long JNICALL Java_com_torchandroid_neuraltalk_lua_LuaManager_initTorch(JNIEnv *env, jobject thiz, jobject assetManager, jstring nativeLibraryDir_) { // get native asset manager. This allows access to files stored in the assets folder AAssetManager* manager = AAssetManager_fromJava(env, assetManager); assert( NULL != manager); const char *nativeLibraryDir = env->GetStringUTFChars(nativeLibraryDir_, 0); lua_State *L = NULL; L = inittorch(manager, nativeLibraryDir);// create a lua_State // load and run file char file[] = "init-only.lua"; int ret; long size = android_asset_get_size(file); if (size != -1) { char *filebytes = android_asset_get_bytes(file); ret = luaL_dobuffer(L, filebytes, size, "init-only"); if (ret == 1) { D("Torch Error doing resource: %s\n", file); D(lua_tostring(L,-1)); } else { D("Torch script ran successfully."); } } return (long) L; }
/** * @brief Initialize the music Lua control system. * * @return 0 on success. */ static int music_luaInit (void) { char *buf; uint32_t bufsize; if (music_disabled) return 0; if (music_lua != NULL) music_luaQuit(); music_lua = nlua_newState(); nlua_loadBasic(music_lua); nlua_loadStandard(music_lua,1); nlua_loadMusic(music_lua,0); /* write it */ /* load the actual Lua music code */ buf = ndata_read( MUSIC_LUA_PATH, &bufsize ); if (luaL_dobuffer(music_lua, buf, bufsize, MUSIC_LUA_PATH) != 0) { ERR("Error loading music file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", MUSIC_LUA_PATH, lua_tostring(music_lua,-1) ); return -1; } free(buf); return 0; }
/** * @brief Initializes a mission. * * @param mission Mission to initialize. * @param misn Data to use. * @param genid 1 if should generate id, 0 otherwise. * @param create 1 if should run create function, 0 otherwise. * @param[out] id ID of the newly created mission. * @return 0 on success. */ static int mission_init( Mission* mission, MissionData* misn, int genid, int create, unsigned int *id ) { char *buf; uint32_t bufsize; int ret; /* clear the mission */ memset( mission, 0, sizeof(Mission) ); /* Create id if needed. */ mission->id = (genid) ? mission_genID() : 0; if (id != NULL) *id = mission->id; mission->data = misn; if (create) { mission->title = strdup(misn->name); mission->desc = strdup("No description."); } /* init Lua */ mission->L = nlua_newState(); if (mission->L == NULL) { WARN("Unable to create a new Lua state."); return -1; } nlua_loadBasic( mission->L ); /* pairs and such */ misn_loadLibs( mission->L ); /* load our custom libraries */ /* load the file */ buf = ndata_read( misn->lua, &bufsize ); if (buf == NULL) { WARN("Mission '%s' Lua script not found.", misn->lua ); return -1; } if (luaL_dobuffer(mission->L, buf, bufsize, misn->lua) != 0) { WARN("Error loading mission file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", misn->lua, lua_tostring(mission->L,-1)); free(buf); return -1; } free(buf); /* run create function */ if (create) { /* Failed to create. */ ret = misn_run( mission, "create"); if (ret) { mission_cleanup(mission); return ret; } } return 0; }
/** * @brief Runs the rescue script if players are stuck. */ static void land_stranded (void) { char *buf; uint32_t bufsize; const char *file = "dat/rescue.lua"; int errf; lua_State *L; /* Nothing to do if there's no rescue script. */ if (!ndata_exists(file)) return; if (rescue_L == NULL) { rescue_L = nlua_newState(); nlua_loadStandard( rescue_L, 0 ); nlua_loadTk( rescue_L ); L = rescue_L; buf = ndata_read( file, &bufsize ); if (luaL_dobuffer(L, buf, bufsize, file) != 0) { WARN("Error loading file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", file, lua_tostring(L,-1)); free(buf); return; } free(buf); } else L = rescue_L; #if DEBUGGING lua_pushcfunction(L, nlua_errTrace); errf = -2; #else /* DEBUGGING */ errf = 0; #endif /* DEBUGGING */ /* Run Lua. */ lua_getglobal(L,"rescue"); if (lua_pcall(L, 0, 0, errf)) { /* error has occurred */ WARN("Rescue: 'rescue' : '%s'", lua_tostring(L,-1)); lua_pop(L,1); } #if DEBUGGING lua_pop(L,1); #endif }
/** * @brief Creates an event. * * @param data Data to base event off of. */ static int event_create( int dataid ) { lua_State *L; uint32_t bufsize; char *buf; Event_t *ev; EventData_t *data; /* Create the event. */ event_nactive++; if (event_nactive > event_mactive) { event_mactive += EVENT_CHUNK; event_active = realloc( event_active, sizeof(Event_t) * event_mactive ); } ev = &event_active[ event_nactive-1 ]; memset( ev, 0, sizeof(Event_t) ); ev->id = ++event_genid; /* Create unique ID. */ /* Add the data. */ ev->data = dataid; data = &event_data[dataid]; /* Open the new state. */ ev->L = nlua_newState(); L = ev->L; nlua_loadStandard(L,0); nlua_loadEvt(L); nlua_loadHook(L); nlua_loadTk(L); /* Load file. */ buf = ndata_read( data->lua, &bufsize ); if (buf == NULL) { WARN("Event '%s' Lua script not found.", data->lua ); return -1; } if (luaL_dobuffer(L, buf, bufsize, data->lua) != 0) { WARN("Error loading event file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", data->lua, lua_tostring(L,-1)); return -1; } free(buf); /* Run Lua. */ event_runLua( ev, "create" ); return 0; }
/** * @brief Initializes the AI. * @param[in] ent Pointer to actor to initialize AI for. * @param[in] type Type of AI (Lua file name without .lua). * @param[in] subtype Subtype of the AI. * @return 0 on success. */ int AIL_InitActor (edict_t * ent, const char *type, const char *subtype) { AI_t *AI; int size; char path[MAX_VAR]; char *fbuf; /* Prepare the AI */ AI = &ent->AI; Q_strncpyz(AI->type, type, sizeof(AI->type)); Q_strncpyz(AI->subtype, subtype, sizeof(AI->type)); /* Create the new Lua state */ AI->L = luaL_newstate(); if (AI->L == NULL) { gi.DPrintf("Unable to create Lua state.\n"); return -1; } /* Register metatables. */ actorL_register(AI->L); pos3L_register(AI->L); /* Register libraries. */ luaL_register(AI->L, AI_METATABLE, AIL_methods); /* Load the AI */ Com_sprintf(path, sizeof(path), "ai/%s.lua", type); size = gi.FS_LoadFile(path, (byte **) &fbuf); if (size == 0) { gi.DPrintf("Unable to load Lua file '%s'.\n", path); return -1; } if (luaL_dobuffer(AI->L, fbuf, size, path)) { gi.DPrintf("Unable to parse Lua file '%s'\n", path); gi.FS_FreeFile(fbuf); return -1; } gi.FS_FreeFile(fbuf); return 0; }
/** * @brief Creates a background Lua state from a script. */ static lua_State* background_create( const char *name ) { uint32_t bufsize; char path[PATH_MAX]; char *buf; lua_State *L; /* Create file name. */ snprintf( path, sizeof(path), "dat/bkg/%s.lua", name ); /* Create the Lua state. */ L = nlua_newState(); nlua_loadStandard(L,1); nlua_loadTex(L,0); nlua_loadCol(L,0); nlua_loadBackground(L,0); /* Open file. */ buf = ndata_read( path, &bufsize ); if (buf == NULL) { WARN("Default background script '%s' not found.", path); lua_close(L); return NULL; } /* Load file. */ if (luaL_dobuffer(L, buf, bufsize, path) != 0) { WARN("Error loading background file: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", path, lua_tostring(L,-1)); free(buf); lua_close(L); return NULL; } free(buf); return L; }
/** * @brief Parses a single faction, but doesn't set the allies/enemies bit. * * @param temp Faction to load data into. * @param parent Parent node to extract faction from. * @return Faction created from parent node. */ static int faction_parse( Faction* temp, xmlNodePtr parent ) { xmlNodePtr node; int player; char buf[PATH_MAX], *dat; uint32_t ndat; /* Clear memory. */ memset( temp, 0, sizeof(Faction) ); temp->name = xml_nodeProp(parent,"name"); if (temp->name == NULL) WARN("Faction from "FACTION_DATA_PATH" has invalid or no name"); player = 0; node = parent->xmlChildrenNode; do { /* Only care about nodes. */ xml_onlyNodes(node); /* Can be 0 or negative, so we have to take that into account. */ if (xml_isNode(node,"player")) { temp->player_def = xml_getFloat(node); player = 1; continue; } xmlr_strd(node,"longname",temp->longname); xmlr_strd(node,"display",temp->displayname); if (xml_isNode(node, "colour")) { temp->colour = col_fromName(xml_raw(node)); continue; } if (xml_isNode(node, "spawn")) { if (temp->sched_state != NULL) WARN("Faction '%s' has duplicate 'spawn' tag.", temp->name); nsnprintf( buf, sizeof(buf), "dat/factions/spawn/%s.lua", xml_raw(node) ); temp->sched_state = nlua_newState(); nlua_loadStandard( temp->sched_state, 0 ); dat = ndata_read( buf, &ndat ); if (luaL_dobuffer(temp->sched_state, dat, ndat, buf) != 0) { WARN("Failed to run spawn script: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", buf, lua_tostring(temp->sched_state,-1)); lua_close( temp->sched_state ); temp->sched_state = NULL; } free(dat); continue; } if (xml_isNode(node, "standing")) { if (temp->state != NULL) WARN("Faction '%s' has duplicate 'standing' tag.", temp->name); nsnprintf( buf, sizeof(buf), "dat/factions/standing/%s.lua", xml_raw(node) ); temp->state = nlua_newState(); nlua_loadStandard( temp->state, 0 ); dat = ndata_read( buf, &ndat ); if (luaL_dobuffer(temp->state, dat, ndat, buf) != 0) { WARN("Failed to run standing script: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", buf, lua_tostring(temp->state,-1)); lua_close( temp->state ); temp->state = NULL; } free(dat); continue; } if (xml_isNode(node, "known")) { faction_setFlag(temp, FACTION_KNOWN); continue; } if (xml_isNode(node, "equip")) { if (temp->equip_state != NULL) WARN("Faction '%s' has duplicate 'equip' tag.", temp->name); nsnprintf( buf, sizeof(buf), "dat/factions/equip/%s.lua", xml_raw(node) ); temp->equip_state = nlua_newState(); nlua_loadStandard( temp->equip_state, 0 ); dat = ndata_read( buf, &ndat ); if (luaL_dobuffer(temp->equip_state, dat, ndat, buf) != 0) { WARN("Failed to run equip script: %s\n" "%s\n" "Most likely Lua file has improper syntax, please check", buf, lua_tostring(temp->equip_state,-1)); lua_close( temp->equip_state ); temp->equip_state = NULL; } free(dat); continue; } if (xml_isNode(node,"logo")) { if (temp->logo_small != NULL) WARN("Faction '%s' has duplicate 'logo' tag.", temp->name); nsnprintf( buf, PATH_MAX, FACTION_LOGO_PATH"%s_small.png", xml_get(node)); temp->logo_small = gl_newImage(buf, 0); nsnprintf( buf, PATH_MAX, FACTION_LOGO_PATH"%s_tiny.png", xml_get(node)); temp->logo_tiny = gl_newImage(buf, 0); continue; } if (xml_isNode(node,"static")) { faction_setFlag(temp, FACTION_STATIC); continue; } if (xml_isNode(node,"invisible")) { faction_setFlag(temp, FACTION_INVISIBLE); continue; } /* Avoid warnings. */ if (xml_isNode(node,"allies") || xml_isNode(node,"enemies")) continue; DEBUG("Unknown node '%s' in faction '%s'",node->name,temp->name); } while (xml_nextNode(node)); if (player==0) DEBUG("Faction '%s' missing player tag.", temp->name); if ((temp->state!=NULL) && faction_isFlag( temp, FACTION_STATIC )) WARN("Faction '%s' has Lua and is static!", temp->name); if ((temp->state==NULL) && !faction_isFlag( temp, FACTION_STATIC )) WARN("Faction '%s' has no Lua and isn't static!", temp->name); return 0; }
/** * @brief Loads specially modified basic stuff. * * @param L Lua State to load the basic stuff into. * @return 0 on success. */ int nlua_loadBasic( lua_State* L ) { int i; const char *override[] = { /* unsafe functions */ "collectgarbage", "dofile", "getfenv", "getmetatable", "load", "loadfile", "loadstring", "rawequal", "rawget", "rawset", "setfenv", /*"setmetatable",*/ "END" }; luaL_openlibs(L); /* replace non-safe functions */ for (i=0; strcmp(override[i],"END")!=0; i++) { lua_pushnil(L); lua_setglobal(L, override[i]); } /* Override print to print in the console. */ lua_register(L, "print", cli_print); lua_register(L, "warn", cli_warn); /* add our own */ lua_register(L, "include", nlua_packfileLoader); return 0; } /** * @brief include( string module ) * * Loads a module into the current Lua state from inside the data file. * * @param module Name of the module to load. * @return An error string on error. */ static int nlua_packfileLoader( lua_State* L ) { const char *filename; char *path_filename; char *buf; int len; uint32_t bufsize; /* Get parameters. */ filename = luaL_checkstring(L,1); /* Check to see if already included. */ lua_getglobal( L, "_include" ); /* t */ if (!lua_isnil(L,-1)) { lua_getfield(L,-1,filename); /* t, f */ /* Already included. */ if (!lua_isnil(L,-1)) { lua_pop(L,2); /* */ return 0; } lua_pop(L,2); /* */ } /* Must create new _include table. */ else { lua_newtable(L); /* t */ lua_setglobal(L, "_include"); /* */ } /* Try to locate the data directly */ buf = NULL; if (ndata_exists( filename )) buf = ndata_read( filename, &bufsize ); /* If failed to load or doesn't exist try again with INCLUDE_PATH prefix. */ if (buf == NULL) { /* Try to locate the data in the data path */ len = strlen(LUA_INCLUDE_PATH)+strlen(filename)+2; path_filename = malloc( len ); nsnprintf( path_filename, len, "%s%s", LUA_INCLUDE_PATH, filename ); if (ndata_exists( path_filename )) buf = ndata_read( path_filename, &bufsize ); free( path_filename ); } /* Must have buf by now. */ if (buf == NULL) { lua_pushfstring(L, "%s not found in ndata.", filename); return 1; } /* run the buffer */ if (luaL_dobuffer(L, buf, bufsize, filename) != 0) { /* will push the current error from the dobuffer */ lua_error(L); return 1; } /* Mark as loaded. */ lua_getglobal(L, "_include"); /* t */ lua_pushboolean(L, 1); /* t b */ lua_setfield(L, -2, filename); /* t */ lua_pop(L, 1); /* cleanup, success */ free(buf); return 0; } /** * @brief Loads the standard Naev Lua API. * * Loads the modules: * - naev * - var * - space * - planet * - system * - jumps * - time * - player * - pilot * - rnd * - diff * - faction * - vec2 * - outfit * - commodity * * Only is missing: * - misn * - tk * - hook * - music * * @param L Lua State to load modules into. * @param readonly Load as readonly (good for sandboxing). * @return 0 on success. */ int nlua_loadStandard( lua_State *L, int readonly ) { int r; r = 0; r |= nlua_loadBasic(L); r |= nlua_loadNaev(L); r |= nlua_loadVar(L,readonly); r |= nlua_loadSpace(L,readonly); /* systems, planets, jumps */ r |= nlua_loadTime(L,readonly); r |= nlua_loadPlayer(L,readonly); r |= nlua_loadPilot(L,readonly); r |= nlua_loadRnd(L); r |= nlua_loadDiff(L,readonly); r |= nlua_loadFaction(L,readonly); r |= nlua_loadVector(L); r |= nlua_loadOutfit(L,readonly); r |= nlua_loadCommodity(L,readonly); r |= nlua_loadNews(L,readonly); return r; }
/** * @brief Loads specially modified basic stuff. * * @param L Lua State to load the basic stuff into. * @return 0 on success. */ int nlua_loadBasic( lua_State* L ) { int i; const char *override[] = { /* unsafe functions */ "collectgarbage", "dofile", "getfenv", "getmetatable", "load", "loadfile", "loadstring", "rawequal", "rawget", "rawset", "setfenv", "setmetatable", "END" }; nlua_load(L,luaopen_base); /* open base. */ /* replace non-safe functions */ for (i=0; strcmp(override[i],"END")!=0; i++) { lua_pushnil(L); lua_setglobal(L, override[i]); } nlua_load(L,luaopen_math); /* open math. */ nlua_load(L,luaopen_table); /* open table. */ nlua_load(L, luaopen_string); /* open string. */ /* add our own */ lua_register(L, "include", nlua_packfileLoader); return 0; } /** * @brief include( string module ) * * Loads a module into the current Lua state from inside the data file. * * @param module Name of the module to load. * @return An error string on error. */ static int nlua_packfileLoader( lua_State* L ) { const char *filename; char *buf; uint32_t bufsize; filename = luaL_checkstring(L,1); /* try to locate the data */ buf = ndata_read( filename, &bufsize ); if (buf == NULL) { lua_pushfstring(L, "%s not found in ndata.", filename); return 1; } /* run the buffer */ if (luaL_dobuffer(L, buf, bufsize, filename) != 0) { /* will push the current error from the dobuffer */ lua_error(L); return 1; } /* cleanup, success */ free(buf); return 0; } /** * @brief Loads the standard NAEV Lua API. * * Loads the modules: * - naev * - space * - planet * - system * - var * - pilot * - time * - player * - diff * - faction * - vec2 * * Only is missing: * - misn * - tk * - hook * - music * * @param L Lua State to load modules into. * @param readonly Load as readonly (good for sandboxing). * @return 0 on success. */ int nlua_loadStandard( lua_State *L, int readonly ) { int r; r = 0; r |= lua_loadNaev(L); r |= lua_loadVar(L,readonly); r |= lua_loadSpace(L,readonly); /* planet, system */ r |= lua_loadTime(L,readonly); r |= lua_loadPlayer(L,readonly); r |= lua_loadPilot(L,readonly); r |= lua_loadRnd(L); r |= lua_loadDiff(L,readonly); r |= lua_loadFaction(L,readonly); r |= lua_loadVector(L); return r; }
int main() { L = luaL_newstate(); luaL_openlibs(L); luaL_requiref(L, "love", initLove, 1); sf2d_init(); // 2D Drawing lib. sftd_init(); // Text Drawing lib. cfguInit(); ptmuInit(); // consoleInit(GFX_BOTTOM, NULL); sf2d_set_clear_color(RGBA8(0x0, 0x0, 0x0, 0xFF)); // Reset background color. osSetSpeedupEnable(true); // Enables CPU speedup for a free performance boost. // Detect if we are running on a .cia, because if we are // we load from RomFS rather than the SD Card. // TODO: Load RomFS from .3dsx's aswell. Result rc = romfsInit(); romfsExists = (rc) ? false : true; // Change working directory if (romfsExists) { chdir("romfs:/"); } else { char cwd[256]; getcwd(cwd, 256); char newCwd[261]; strcat(newCwd, cwd); strcat(newCwd, "game"); chdir(newCwd); } luaL_dobuffer(L, boot_lua, boot_lua_size, "boot"); // Do some setup Lua side. // If main.lua exists, execute it. // If not then just load the nogame screen. if (fileExists("main.lua")) { if (luaL_dofile(L, "main.lua")) displayError(); } else { if (luaL_dobuffer(L, nogame_lua, nogame_lua_size, "nogame")) displayError(); } if (luaL_dostring(L, "love.timer.step()")) displayError(); if (luaL_dostring(L, "if love.load then love.load() end")) displayError(); while (aptMainLoop()) { if (shouldQuit) { if (forceQuit) break; bool shouldAbort = false; // lua_getfield(L, LUA_GLOBALSINDEX, "love"); // lua_getfield(L, -1, "quit"); // lua_remove(L, -2); // if (!lua_isnil(L, -1)) { // lua_call(L, 0, 1); // shouldAbort = lua_toboolean(L, 1); // lua_pop(L, 1); // }; TODO: Do this properly. if (luaL_dostring(L, "if love.quit then love.quit() end")) displayError(); if (!shouldAbort && !errorOccured) break; } // Quit event if (!errorOccured) { if (luaL_dostring(L, "love.keyboard.scan()\n" "love.timer.step()\n" "if love.update then love.update(love.timer.getDelta()) end")) { displayError(); } // Top screen // Left side sf2d_start_frame(GFX_TOP, GFX_LEFT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); // Right side if (is3D) { sf2d_start_frame(GFX_TOP, GFX_RIGHT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); } // Bot screen sf2d_start_frame(GFX_BOTTOM, GFX_LEFT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); luaL_dostring(L, "love.graphics.present()"); } else { hidScanInput(); u32 kTempDown = hidKeysDown(); if (kTempDown & KEY_START) { forceQuit = true; shouldQuit = true; } char *errMsg = lua_tostring(L, -1); sf2d_start_frame(GFX_TOP, GFX_LEFT); lua_getfield(L, LUA_GLOBALSINDEX, "love"); lua_getfield(L, -1, "errhand"); lua_remove(L, -2); if (!lua_isnil(L, -1)) { lua_pushstring(L, errMsg); lua_call(L, 1, 0); } sf2d_end_frame(); sf2d_start_frame(GFX_BOTTOM, GFX_LEFT); lua_getfield(L, LUA_GLOBALSINDEX, "love"); lua_getfield(L, -1, "errhand"); lua_remove(L, -2); if (!lua_isnil(L, -1)) { lua_pushstring(L, errMsg); lua_call(L, 1, 0); } sf2d_end_frame(); luaL_dostring(L, "love.graphics.present()"); } } luaL_dostring(L, "love.audio.stop()"); lua_close(L); sftd_fini(); sf2d_fini(); cfguExit(); ptmuExit(); if (soundEnabled) ndspExit(); if (romfsExists) romfsExit(); return 0; }