Exemple #1
0
static int docall(lua_State *L, int narg, int clear)
{
    int status;
    int base = lua_gettop(L) - narg;  /* function index */
    lua_pushcfunction(L, traceback);  /* push traceback function */
    lua_insert(L, base);  /* put it under chunk and args */
    signal(SIGINT, laction);
    status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
    signal(SIGINT, SIG_DFL);
    lua_remove(L, base);  /* remove traceback function */
    /* force a complete garbage collection in case of errors */
    if (status != 0)
        lua_gc(L, LUA_GCCOLLECT, 0);
    return status;
}
Exemple #2
0
// returns 0 on error
static int callfunction (lua_State *L, int narg, int clear, const char *key)
{
  int status;
  int base = lua_gettop(L) - narg +1;  /* function index */
  lua_getfield(L,LUA_REGISTRYINDEX,key); // get the function key to be fetched
  lua_insert(L, base);  /* put it under chunk and args */

  lua_pushcfunction(L, traceback);  /* push traceback function */
  lua_insert(L, base);  /* put it under chunk and args */
  status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  lua_remove(L, base);  /* remove traceback function */
  /* force a complete garbage collection in case of errors */
  if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  return status;
}
Exemple #3
0
static int luaB_collectgarbage (lua_State *L) {
  static const char *const opts[] = {"stop", "restart", "collect",
    "count", "step", "setpause", "setstepmul", NULL};
  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL};
  int o = luaL_checkoption(L, 1, "collect", opts);
  int ex = luaL_optint(L, 2, 0);
  int res = lua_gc(L, optsnum[o], ex);
  switch (optsnum[o]) {
    case LUA_GCCOUNT: {
      int b = lua_gc(L, LUA_GCCOUNTB, 0);
      lua_pushnumber(L, res + ((lua_Number)b/1024));
      return 1;
    }
    case LUA_GCSTEP: {
      lua_pushboolean(L, res);
      return 1;
    }
    default: {
      lua_pushnumber(L, (lua_Number)res);
      return 1;
    }
  }
}
Exemple #4
0
//==============================================================================
Error LuaBinder::evalString(const CString& str)
{
	Error err = ErrorCode::NONE;
	int e = luaL_dostring(m_l, &str[0]);
	if(e)
	{
		ANKI_LOGE("%s", lua_tostring(m_l, -1));
		lua_pop(m_l, 1);
		err = ErrorCode::USER_DATA;
	}

	lua_gc(m_l, LUA_GCCOLLECT, 0);

	return err;
}
Exemple #5
0
static void websocketclient_onCloseCallback(ws_info *ws, int errorCode) {
  NODE_DBG("websocketclient_onCloseCallback\n");

  lua_State *L = lua_getstate();

  if (ws == NULL || ws->reservedData == NULL) {
    luaL_error(L, "Client websocket is nil.\n");
    return;
  }
  ws_data *data = (ws_data *) ws->reservedData;  

  if (data->onClose != LUA_NOREF) {
    lua_rawgeti(L, LUA_REGISTRYINDEX, data->onClose); // load the callback function
    lua_rawgeti(L, LUA_REGISTRYINDEX, data->self_ref);  // pass itself, #1 callback argument
    lua_pushnumber(L, errorCode); // pass the error code, #2 callback argument
    lua_call(L, 2, 0);
  }

  // free self-reference to allow gc (no futher callback will be called until next ws:connect())
  lua_gc(L, LUA_GCSTOP, 0); // required to avoid freeing ws_data
  luaL_unref(L, LUA_REGISTRYINDEX, data->self_ref);
  data->self_ref = LUA_NOREF;
  lua_gc(L, LUA_GCRESTART, 0);
}
Exemple #6
0
//*****************************************************************************
LuaStack LuaUtils::NewLuaStack(bool openlibs, bool debug, const char *name)
{
    LuaStack new_stack = lua_open();

    if (openlibs)
        luaL_openlibs(new_stack);

    // Force lua garbage collector to be non incremental
    lua_gc(new_stack, LUA_GCSETSTEPMUL, 100000000);

    if (debug)
        LunarProbe::GetInstance()->Attach(new_stack, name);

    return new_stack;
}
Exemple #7
0
int main(void)
{
	print_sysinfo();

	/* File system Driver setup */

	if( mmcfs_setup() ) {
		printf("[!] Filesystem setup failed.\n\n");
		return -1;
	}
	printf("\n");

	/* Lua initialize (5.2.0) */

	lua_State *L = luaL_newstate();	// create state 
	if( L == NULL ) {
		printf("[!] cannot create state: not enough memory\n\n");
		return -1;
	}

	lua_gc(L, LUA_GCSTOP, 0);	// stop collector during initialization 
	luaL_openlibs(L);			// open libraries 
	lua_gc(L, LUA_GCRESTART, 0);

	printf(LUA_COPYRIGHT "\n");	// print version 

	/* script file load & run */

	printf("autorun file = %s\n\n",LUA_AUTORUN_FILE);
	if( luaL_dofile(L, LUA_AUTORUN_FILE) != 0 ) printf("%s\n",lua_tostring(L,-1));


	lua_close(L);

	return 0;
}
void KScriptManager::Activate()
{
    if (m_bReload)
    {
        Load();
        m_bReload = false;
    }

    CallActivateScript();

    if (g_pSO3World->m_nGameLoop % (GAME_FPS * 8) == 0)
    {
        lua_gc(m_piScript->GetLuaState(), LUA_GCCOLLECT, 0);
    }
}
Exemple #9
0
// Load a script from a MYFILE
static inline void LUA_LoadFile(MYFILE *f, char *name)
{
	if (!name)
		name = wadfiles[f->wad]->filename;
	CONS_Printf("Loading Lua script from %s\n", name);
	if (!gL) // Lua needs to be initialized
		LUA_ClearState();
	lua_pushinteger(gL, f->wad);
	lua_setfield(gL, LUA_REGISTRYINDEX, "WAD");
	if (luaL_loadbuffer(gL, f->data, f->size, va("@%s",name)) || lua_pcall(gL, 0, 0, 0)) {
		CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL,-1));
		lua_pop(gL,1);
	}
	lua_gc(gL, LUA_GCCOLLECT, 0);
}
Exemple #10
0
static int _launch(struct pixel *ctx, struct lua *lua, const char *param) {
	const char *loader, *path, *cpath, *service_path;
	lua_State *L = lua->L;
	lua->ctx = ctx;
	lua_gc(L, LUA_GCSTOP, 0);
	luaL_openlibs(L);
	lua_pushlightuserdata(L, ctx);
	lua_setfield(L, LUA_REGISTRYINDEX, "pixel");
	luaL_requiref(L, "pixel.c", pixel_lua, 0);
	luaL_requiref(L, "pixel.serial", pixel_serial, 0);
	lua_settop(L, 0);
	path = optstring(ctx, "lua_path", "./?.lua;./lualib/?.lua");
	lua_pushstring(L, path);
	lua_setglobal(L, "LUA_PATH");
	cpath = optstring(ctx, "lua_cpath", "./?.so");
	lua_pushstring(L, cpath);
	lua_setglobal(L, "LUA_CPATH");
	service_path = optstring(ctx, "lua_service", "./service/?.lua");
	lua_pushstring(L, service_path);
	lua_setglobal(L, "LUA_SERVICE");
	lua_pushcfunction(L, traceback);
	assert(lua_gettop(L) == 1);
	loader = optstring(ctx, "lua_loader", "./lualib/loader.lua");
	if (LUA_OK != luaL_loadfile(L, loader)) {
		pixel_log(ctx, "luaL_loadfile %s\n", lua_tostring(L, -1));
		return -1;
	}
	lua_pushstring(L, param);
	if (LUA_OK != lua_pcall(L, 1, 0, 1)) {
		pixel_log(ctx, "lua loader %s\n", lua_tostring(L, -1));
		return -1;
	}
	lua_settop(L, 0);
	lua_gc(L, LUA_GCRESTART, 0);
	return 0;
}
Exemple #11
0
void LuaInterface::collectGarbage()
{
    // prevents recursive collects
    static bool collecting = false;
    if(!collecting) {
        collecting = true;

        // we must collect two times because __gc metamethod
        // is called on uservalues only the second time
        for(int i=0;i<2;++i)
            lua_gc(L, LUA_GCCOLLECT, 0);

        collecting = false;
    }
}
Exemple #12
0
int intraFont_load(lua_State *L)
{
	int argc = lua_gettop(L);
	if (argc != 1) return luaL_error(L, "intraFont.load(fontpath): must be called with only one argument");
	lua_gc(L, LUA_GCCOLLECT, 0);
		intraFont *font = intraFontLoad(luaL_checkstring(L, 1), INTRAFONT_CACHE_ASCII);
	
	if (font == NULL) return luaL_error(L, "intraFont.load: error loading font.");
	
	intraFont **luaFont;
	luaFont = pushintraFont(L);	
	*luaFont = font;	
	
	return 1;
}
Exemple #13
0
static int pmain (lua_State *L) {
  struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
  char **argv = s->argv;
  int script;
  int has_i = 0, has_v = 0, has_e = 0;
  globalL = L;
  if (argv[0] && argv[0][0]) progname = argv[0];
  lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
  luaL_openlibs(L);  /* open libraries */
  lua_gc(L, LUA_GCRESTART, 0);
  s->status = handle_luainit(L);
  if (s->status != 0) return 0;
  script = collectargs(argv, &has_i, &has_v, &has_e);
  if (script < 0) {  /* invalid args? */
    print_usage();
    s->status = 1;
    return 0;
  }

  if (has_v) print_version();
  s->status = runargs(L, argv, (script > 0) ? script : s->argc);
  if (s->status != 0) return 0;
  if (script)
    s->status = handle_script(L, argv, script);
  if (s->status != 0) return 0;
  if (has_i)
    dotty(L);
  else if (script == 0 && !has_e && !has_v) {
    if (lua_stdin_is_tty()) {
      print_version();
      dotty(L);
    }
    else dofile(L, NULL);  /* executes stdin as a file */
  }
  return 0;
}
Exemple #14
0
mMatComplex *
qlua_newMatComplex(lua_State *L, int sl, int sr)
{
    mMatComplex *m = qlua_newMatrix(L, sizeof (mMatComplex), mtnMatComplex);
    m->l_size = sl;
    m->r_size = sr;
    m->m = gsl_matrix_complex_calloc(sl, sr);
    if (m->m == 0) {
        lua_gc(L, LUA_GCCOLLECT, 0);
        m->m = gsl_matrix_complex_calloc(sl, sr);
        if (m->m == 0)
            luaL_error(L, "not enough memory");
    }
    return m;
}
Exemple #15
0
	int include(lua_State * L)
	{
		int n = lua_gettop(L);

		if( n != 1 )
			return luaL_error(L, "Function requires a single parameter.");

		int type = lua_type(L, 1);

		if(type != LUA_TSTRING)
			return luaL_error(L, "Function requires parameter of type string.");
		
		const char * filename = lua_tostring(L, 1);

		// Get the file.
		love::pFile * file = filesystem->getFile(filename, love::FILE_READ);

		if(!(*file)->load())
		{
			delete file;
			std::stringstream ss;
			ss << "Could not include file \"" << filename << "\".";
			return luaL_error(L, ss.str().c_str());
		}

		int status = luaL_loadbuffer (L, (const char *)(*file)->getData(), 
			(*file)->getSize(), (*file)->getFilename().c_str());

		delete file;

		if(status != 0)
		{
			compile_error(L, status);
			return 0;
		}

		// Stealing this from LuaGame.
		int narg = 0, nres = 0;
		int base = lua_gettop(L) - narg;  /* function index */
		lua_pushcfunction(L, runtime_error);  /* push traceback function */
		lua_insert(L, base);  /* put it under chunk and args */
		status = lua_pcall(L, narg, nres, base);
		lua_remove(L, base);  /* remove traceback function */
		/* force a complete garbage collection in case of errors */
		if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);

		return 0;
	}
Exemple #16
0
int Lua_Close(lua_State *L)
{
	if(!Lua_State)
		return 0;
	if(L)
	{
		Lua_requestClose = true;
		return 0;
	}

	log_info("Closing Lua");

	App_UsingDisplay = false;

	if(App_UseFullScreen)
	{
		App_UseFullScreen = false;
		Console_Show = true;
	}

	if(Lua_hasClose)
	{
		lua_getglobal(Lua_State, "close");
		if(lua_pcall(Lua_State, 0, 0, 0) != 0)
		{
			const char *Error = lua_tostring(Lua_State, -1);
			fprintf(Log, "Error close : %s\n", Error);
		}
	}

	LuaLibrary_Close();

    lua_gc(Lua_State, LUA_GCCOLLECT, 0);
    lua_close(Lua_State);
    Lua_State = NULL;

    log_info("Lua closed");

    Console_Update();

    fclose(Log);
    fclose(Input);
    Log = Input = NULL;

    Log_ReadAt = 2;
    log_info("Done closing Lua");
	return 0;
}
Exemple #17
0
static int jiveL_quit(lua_State *L) {

	/* de-reference all windows */
	jiveL_getframework(L);
	lua_pushnil(L);
	lua_setfield(L, -2, "windowStack");
	lua_pop(L, 1);

	/* force lua GC */
	lua_gc(L, LUA_GCCOLLECT, 0);

	/* quit SDL */
	SDL_Quit();

	return 0;
}
Exemple #18
0
int CCLuaStack::executeString(const char *codes)
{
    ++m_callFromLua;
    int nRet = luaL_dostring(m_state, codes);
    --m_callFromLua;
    CC_ASSERT(m_callFromLua >= 0);
    lua_gc(m_state, LUA_GCCOLLECT, 0);
    
    if (nRet != 0)
    {
        CCLOG("[LUA ERROR] %s", lua_tostring(m_state, -1));
        lua_pop(m_state, 1);
        return nRet;
    }
    return 0;
}
Exemple #19
0
static int Socket_new(lua_State *L){
	int argc = lua_gettop(L);

	if (argc != 2 && argc != 1){
		return luaL_error(L, "Argument error: geSocket.new([hostname, ]port) takes one or two arguments.");
	}
	lua_gc(L, LUA_GCCOLLECT, 0);

	if(argc == 1){
		*pushNewSocket(L) = geCreateSocket( GE_SOCKET_TYPE_SERVER, "0.0.0.0", (int)luaL_checknumber(L, 1), GE_PORT_TYPE_TCP );
	}else{
		*pushNewSocket(L) = geCreateSocket( GE_SOCKET_TYPE_CLIENT, luaL_checkstring(L, 1), (int)luaL_checknumber(L, 2), GE_PORT_TYPE_TCP );
	}

	return 1;
}
Exemple #20
0
static int report(lua_State *L, int status)
{
    if (status != LUA_OK && !lua_isnil(L, -1))
    {
        const char *msg = lua_tostring(L, -1);
        if (msg == NULL)
            msg = "(error object is not a string)";

        l_message(progname, msg);
        lua_pop(L, 1);
        /* force a complete garbage collection in case of errors */
        lua_gc(L, LUA_GCCOLLECT, 0);
    }

    return status;
}
Exemple #21
0
 int ScriptVM::do_invoke(int nargs, int clear)
 {
     int status = 0;
     lua_State* state = stack_;
     // get function index
     int base = lua_gettop(state) - nargs;
     // push traceback function
     lua_pushcfunction(state, traceback);
     lua_insert(state, base);
     status = lua_pcall(state, nargs, (clear ? 0 : LUA_MULTRET), base);
     lua_remove(state, base);
     // force a complete garbage collection in case of error
     if(status != 0) {
         lua_gc(state, LUA_GCCOLLECT, 0);
     }
     return status;
 }
Exemple #22
0
void LuaAudio::run_samples(__int64 start, __int64 count, void *buf){
	//Set sample data
	samples.start = start;
	samples.count = count;
	samples.buf = buf;
	//Run framework
	lua_getfield(L, LUA_GLOBALSINDEX, "GetSamples");
	if(lua_isfunction(L,-1)){
		lua_pushnumber(L, start);
		lua_pushnumber(L, (double)start / info.sample_rate * 1000);
		lua_pushnumber(L, count);
		if(lua_pcall(L, 3, 0, 0))
			throw lua_tostring(L,-1);
		lua_gc(L, LUA_GCCOLLECT, 0);
	}else
		lua_pop(L,-1);
}
Exemple #23
0
static int log_stat_timer(int msgid, void *userdata){
    bbuf_stat();
    rbuf_stat();
    port_stat();
    pbc_stat();
    timer_stat();
    LOG_STAT("==========LOG==========");
    LOG_STAT("error:(%d), warning:(%d)", s_error_counter, s_warning_counter);
    
    LOG_STAT("==========LUA==========");
    LOG_STAT("memory:(%dk) stack top(%d)", lua_gc(L, LUA_GCCOUNT, 0), lua_gettop(L));

    LOG_STAT("==========MEM==========");
    //LOG_STAT("used:%dk rss:%dk", zmalloc_used_memory()/1024, zmalloc_get_rss()/1024);

    return 1;
}
Exemple #24
0
int _tmain(int argc, _TCHAR* argv[])
{
	std::cout << "Working..." << std::endl;

	lua_State* L = lua_open();
	luaL_openlibs( L );

	HRESULT hr = InitD3D();
	int res;

	if( FAILED(hr) )
		return 255;

	const char* startScript = argv[1];

	if( argc < 2 )
		return -1;

	bind_builtin_lua_scripts( L );

	image_lua_bind( L );
	sampler_lua_bind( L );

	{//write to package.loaded.luaimg that package loaded
		lua_getglobal( L, "package" );
		lua_getfield( L, -1, "loaded" );
		lua_pushboolean( L, 1 );
		lua_setfield( L, -2, "luaimg" );
	}

	int narg = getargs(L, argv, 1); 
	lua_setglobal(L, "arg");

	res = luaL_dofile( L, startScript );
	if(res)
	{
		printError( L );
		return 255;
	}

	lua_gc( L, LUA_GCCOLLECT, 0 );

	lua_close( L );
	
	return 0;
}
Exemple #25
0
void LuaBinding::unload()
{
  for (int i = 0; i < ninstances; i++) {
    pthread_mutex_lock(&(this->mutex[i]));
    if (this->L[i]) {
      lua_gc(this->L[i], LUA_GCCOLLECT, 0);
      lua_close(this->L[i]);
      this->L[i] = NULL;
    }
    pthread_mutex_unlock(&(this->mutex[i]));
  }

  if (path) {
    free(path);
    path = NULL;
  }
}
Exemple #26
0
    Script::Script(Engine& engine, Timer& timer, Keyboard& keyboard, Mouse& mouse, Audio& audio, Screen& screen)
        : L(luaL_newstate()),
        engine_(engine),
        timer_(timer),
        keyboard_(keyboard),
        mouse_(mouse),
        audio_(audio),
        screen_(screen)
    {
        luaL_openlibs(L);

        lua_gc(L, LUA_GCSETSTEPMUL, 400);

        // Allow the static script methods to be able to use instance variables,
        // by looking up with the lua_State.
        instances[L] = this;

        // Load library functions.
        script::initLibrary(L);

        luaL_dostring(L,
            "function plum.RequireModuleFromPit(modulename)\r\n"
                // Find the source in a .pit file.
            "    local modulepath = string.gsub(modulename, '%.', '/')\r\n"
            "    for path in string.gmatch(package.path, '([^;]+)') do\r\n"
            "        local filename = string.gsub(path, '%?', modulepath)\r\n"
            "        local f = plum.File(filename, 'r')\r\n"
            "        if f then\r\n"
                        // Read and compile the chunk.
            "            local chunk = assert(loadstring(f:readFully(), '@' .. filename))\r\n"
            "            f:close()\r\n"
                        // Success!
            "            return chunk\r\n"
            "        end\n"
            "    end\n"
                // Failed to open it.
            "    return '\\r\\n\\tno pit module \\'' .. modulename .. '\\''\r\n"
            "end\r\n"
            "\r\n"

            // Add a few more package path rules that agree with our loader a lot more.
            "package.path = package.path .. ';?.lua;?/init.lua;?\\\\init.lua'\r\n"
            // Install the loader so that it's called just before the DLL loader
            "table.insert(package.loaders, 3, plum.RequireModuleFromPit)\r\n"
        );
    }
Exemple #27
0
Actor* Actor::Create(const String& archetype)
{
	lua_State* L = LuaScriptingModule::GetLuaState();
	lua_getglobal(L, "Actor_CreateAndRegister");
	lua_pushstring(L, archetype.c_str());
	if (lua_pcall(L, 1, 0, 0))
	{
		const char* errs = lua_tostring(L, -1);
		sysLog.Printf("ERROR: %s\n", errs);
		// error, will be in the stack trace
		lua_gc(L, LUA_GCCOLLECT, 0); // garbage collect on error
		return NULL;
	}
	else
	{
		return _scriptCreatedActor;
	}
}
Exemple #28
0
static int IndiceArray_new(lua_State *L){
	int argc = lua_gettop(L); 

	if (argc != 1){
		return luaL_error(L, "Argument error: geIndiceArray.new(size) must take one argument.");
	}
	lua_gc(L, LUA_GCCOLLECT, 0);

	int size = luaL_checkint(L, 1);
	if(size <= 0){
		return luaL_error(L, "Argument error: geIndiceArray.new(size) : size must be greater than 0");
	}

	INDICE_ARRAY_TYPE* array = (INDICE_ARRAY_TYPE*)geMalloc(sizeof(INDICE_ARRAY_TYPE) * size);
	alloc_IndiceArray(L, array, size);

	return 1;
}
Exemple #29
0
void ScriptController::finalizeGame()
{
    std::vector<std::string> finalizeCallbacks = _callbacks[FINALIZE]; // no & : makes a copy of the vector

	// Remove any registered callbacks so they don't get called after shutdown
	for (unsigned int i = 0; i < CALLBACK_COUNT; i++)
        _callbacks[i].clear();

	// Fire script finalize callbacks
    for (size_t i = 0; i < finalizeCallbacks.size(); ++i)
        executeFunction<void>(finalizeCallbacks[i].c_str());

    // Perform a full garbage collection cycle.
	// Note that this does NOT free any global variables declared in scripts, since 
	// they are stored in the global state and are still referenced. Only after 
	// closing the state (lua_close) will those variables be released.
    lua_gc(_lua, LUA_GCCOLLECT, 0);
}
Exemple #30
0
static int docall(lua_State *L, int narg, int nres)
{
  int status;
  int base = lua_gettop(L) - narg;  /* function index */
  lua_pushcfunction(L, traceback);  /* push traceback function */
  lua_insert(L, base);  /* put it under chunk and args */
#if !LJ_TARGET_CONSOLE
  signal(SIGINT, laction);
#endif
  status = lua_pcall(L, narg, nres, base);
#if !LJ_TARGET_CONSOLE
  signal(SIGINT, SIG_DFL);
#endif
  lua_remove(L, base);  /* remove traceback function */
  /* force a complete garbage collection in case of errors */
  if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  return status;
}