コード例 #1
0
ファイル: LuaPlus.cpp プロジェクト: brock7/TianLong
void LuaState::Init( bool initStandardLibrary )
{
	// Register some basic functions with Lua.
	if (initStandardLibrary)
	{
		// A "bug" in Lua 5.01 causes stack entries to be left behind.
		LuaAutoBlock autoBlock(this);
		luaopen_base(m_state);
		luaopen_table( m_state );
		luaopen_io(m_state);
		luaopen_string(m_state);
		luaopen_wstring(m_state);
		luaopen_math(m_state);
		luaopen_debug(m_state);
#ifndef _WIN32_WCE
		luaopen_loadlib(m_state);
#endif _WIN32_WCE

		ScriptFunctionsRegister( this );

		GetGlobals().Register("LuaDumpGlobals", LS_LuaDumpGlobals);
		GetGlobals().Register("LuaDumpObject", LS_LuaDumpObject);
		GetGlobals().Register("LuaDumpFile", LS_LuaDumpFile);
	}

	GetGlobals().Register("LOG", LS_LOG);
	GetGlobals().Register("_ALERT", LS_LOG);

	lua_atpanic( m_state, FatalError );
}
コード例 #2
0
//============================================================================
// bool CLuaVirtualMachine::InitialiseVM
//---------------------------------------------------------------------------
// Initialises the VM, open lua, makes sure things are OK
//
// Parameter   Dir      Description
// ---------   ---      -----------
// None.
//
// Return
// ------
// Success.
//
//============================================================================
bool CLuaVirtualMachine::InitialiseVM (void)
{
   // Open Lua!
   if (Ok ()) DestroyVM ();

   m_pState = lua_open ();

   if (m_pState) 
   {
      m_fIsOk = true;

      // Load util libs into lua
      luaopen_base (m_pState);
      luaopen_table (m_pState);
      luaopen_string (m_pState);
      luaopen_math (m_pState);
      luaopen_debug (m_pState);
      //luaopen_io (m_pState);
      //luaopen_loadlib (m_pState);

      // setup global printing (trace)
      lua_pushcclosure (m_pState, printMessage, 0);
      lua_setglobal (m_pState, "trace");

      lua_atpanic (m_pState, (lua_CFunction) CLuaVirtualMachine::Panic);

      return true;
   }

   return false;
}
コード例 #3
0
ファイル: lua_class.cpp プロジェクト: cherry-wb/pint
  void Lua::done(int exitstatus){

#ifdef linux
    fflush(stdin);
    fflush(stdout);
    fflush(stderr);
    dup2(fileno(lua_std_in),STDIN_FILENO); //this stuff recovers stdin/stdout/stderr after the instrumentated process closed them
    dup2(fileno(lua_std_out),STDOUT_FILENO);
    dup2(fileno(lua_std_err),STDERR_FILENO);
#else
    freopen ("closing_log_stdout.txt","w",stdout);
    freopen ("closing_log_stderr.txt","w",stderr);
    fprintf(stderr,"error output:\n");
    printf("std output:\n");
#endif

    luaopen_debug(L);

    //lua_pushcfunction(L, errorHandler);

    lua_getglobal(L, "debug"); //addes debug backtrace as formater for errors
    lua_getfield(L, -1, "traceback");

    lua_getglobal(L, "at_exit");
    lua_pushnumber(L, exitstatus);
    report_errors(lua_pcall(L, 1, 0, -3)); // last -3 = debug.backtrace is used as error function
    fclose(stdout);
    fclose(stderr);
  }
コード例 #4
0
    void LuaLibrary::VLoadCoreModule(
                const unsigned int selectedModule)
    {
        CoreModules coreModule =
                        static_cast<CoreModules>(selectedModule);
        
        switch(coreModule)
        {
            case LuaLibrary::CoreModules::Base:
                luaopen_base(m_pLuaState);
                break;
            
            case LuaLibrary::CoreModules::Debug:
                luaopen_debug(m_pLuaState);
                break;
                
            case LuaLibrary::CoreModules::Math:
                luaopen_math(m_pLuaState);
                break;

            case LuaLibrary::CoreModules::Os:
                luaopen_os(m_pLuaState);
                break;
                
            case LuaLibrary::CoreModules::String:
                luaopen_string(m_pLuaState);
                break;
                
            case LuaLibrary::CoreModules::Table:
                luaopen_table(m_pLuaState);
                break;
        }
    }
コード例 #5
0
ファイル: LuaHandlerBase.cpp プロジェクト: Rincevent/lbanet
/***********************************************************
constructor
***********************************************************/
LuaHandlerBase::LuaHandlerBase()
    : m_creatingthread(-1)
{
    try
    {
        // Create a new lua state
        m_LuaState = lua_open();

        // Connect LuaBind to this lua state
        luabind::open(m_LuaState);

        //open standard libs
        luaopen_base(m_LuaState);
        luaopen_table(m_LuaState);
        luaopen_string(m_LuaState);
        luaopen_math(m_LuaState);
        luaopen_debug(m_LuaState);
        //luaopen_package(m_LuaState);

        //luaL_openlibs(m_LuaState);
    }
    catch(const std::exception &error)
    {
        LogHandler::getInstance()->LogToFile(std::string("Exception initializing LUA for base lua: ") + error.what(), 0);
    }
}
コード例 #6
0
ファイル: ltapi.c プロジェクト: acassis/lintouch
int ltapi_libraries_load( lua_State * L )
{
    /* load required library and discard any possible results remaining at
     * the stack */

    luaopen_base( L );
    lua_settop( L, 0 );

    luaopen_table( L );
    lua_settop( L, 0 );

    luaopen_io( L );
    lua_settop( L, 0 );

    luaopen_string( L );
    lua_settop( L, 0 );

    luaopen_math( L );
    lua_settop( L, 0 );

    luaopen_debug( L );
    lua_settop( L, 0 );

    luaopen_loadlib( L );
    lua_settop( L, 0 );

    return 0;
}
コード例 #7
0
ファイル: load81.c プロジェクト: cobrajs/load81
void resetProgram(void) {
    char *initscript =
        "keyboard={}; keyboard['pressed']={};"
        "mouse={}; mouse['pressed']={};"
        "sprites={}";

    l81.epoch = 0;
    if (l81.L) lua_close(l81.L);
    l81.L = lua_open();
    luaopen_base(l81.L);
    luaopen_table(l81.L);
    luaopen_string(l81.L);
    luaopen_math(l81.L);
    luaopen_debug(l81.L);
    setNumber("WIDTH",l81.width);
    setNumber("HEIGHT",l81.height);
    luaL_loadbuffer(l81.L,initscript,strlen(initscript),"initscript");
    lua_pcall(l81.L,0,0,0);

    /* Make sure that mouse parameters make sense even before the first
     * mouse event captured by SDL */
    setTableFieldNumber("mouse","x",0);
    setTableFieldNumber("mouse","y",0);
    setTableFieldNumber("mouse","xrel",0);
    setTableFieldNumber("mouse","yrel",0);

    /* Register API */
    lua_pushcfunction(l81.L,fillBinding);
    lua_setglobal(l81.L,"fill");
    lua_pushcfunction(l81.L,filledBinding);
    lua_setglobal(l81.L,"filled");
    lua_pushcfunction(l81.L,rectBinding);
    lua_setglobal(l81.L,"rect");
    lua_pushcfunction(l81.L,ellipseBinding);
    lua_setglobal(l81.L,"ellipse");
    lua_pushcfunction(l81.L,backgroundBinding);
    lua_setglobal(l81.L,"background");
    lua_pushcfunction(l81.L,triangleBinding);
    lua_setglobal(l81.L,"triangle");
    lua_pushcfunction(l81.L,lineBinding);
    lua_setglobal(l81.L,"line");
    lua_pushcfunction(l81.L,textBinding);
    lua_setglobal(l81.L,"text");
    lua_pushcfunction(l81.L,setFPSBinding);
    lua_setglobal(l81.L,"setFPS");
    lua_pushcfunction(l81.L,getpixelBinding);
    lua_setglobal(l81.L,"getpixel");
    lua_pushcfunction(l81.L,spriteBinding);
    lua_setglobal(l81.L,"sprite");
    lua_pushcfunction(l81.L,polygonBinding);
    lua_setglobal(l81.L,"polygon");

    initSpriteEngine(l81.L);

    /* Start with a black screen */
    fillBackground(l81.fb,0,0,0);
}
コード例 #8
0
ファイル: z_lua_state.hpp プロジェクト: JerkWisdom/zpublic
 int open_debug()
 {
     if (L)
     {
         luaopen_debug(L);
         return 0;
     }
     return -1;
 }
コード例 #9
0
ファイル: AmjuLua.cpp プロジェクト: jason-amju/amjulib
Lua::Lua()
{
    m_pL = luaL_newstate(); // NOT lua_open()

    // Include all lua libraries.
    luaL_openlibs(m_pL);

    luaopen_debug(m_pL); // we want to make it as easy as possible to debug scripts!
}
コード例 #10
0
ファイル: CEGUILua.cpp プロジェクト: B2O/IV-Network
/*************************************************************************
	Constructor (creates Lua state)
*************************************************************************/
LuaScriptModule::LuaScriptModule(lua_State* state) :
    d_ownsState(state == 0),
    d_state(state),
    d_errFuncIndex(LUA_NOREF),
    d_activeErrFuncIndex(LUA_NOREF)
{
    // initialise and create a lua_State if one was not provided
    if (!d_state)
    {
        #if CEGUI_LUA_VER >= 51
            static const luaL_Reg lualibs[] = {
                {"", luaopen_base},
                {LUA_LOADLIBNAME, luaopen_package},
                {LUA_TABLIBNAME, luaopen_table},
                {LUA_IOLIBNAME, luaopen_io},
                {LUA_OSLIBNAME, luaopen_os},
                {LUA_STRLIBNAME, luaopen_string},
                {LUA_MATHLIBNAME, luaopen_math},
            #if defined(DEBUG) || defined (_DEBUG)
                    {LUA_DBLIBNAME, luaopen_debug},
            #endif
                {0, 0}
            };
        #endif /* CEGUI_LUA_VER >= 51 */

        // create a lua state
        d_ownsState = true;
#if LUA_VERSION_NUM > 501
        d_state = luaL_newstate();
#else
        d_state = lua_open();
#endif

        // init all standard libraries
        #if CEGUI_LUA_VER >= 51
                const luaL_Reg *lib = lualibs;
                for (; lib->func; lib++)
                {
                    lua_pushcfunction(d_state, lib->func);
                    lua_pushstring(d_state, lib->name);
                    lua_call(d_state, 1, 0);
                }
        #else /* CEGUI_LUA_VER >= 51 */
            luaopen_base(d_state);
            luaopen_io(d_state);
            luaopen_string(d_state);
            luaopen_table(d_state);
            luaopen_math(d_state);
            #if defined(DEBUG) || defined (_DEBUG)
                luaopen_debug(d_state);
            #endif
        #endif /* CEGUI_LUA_VER >= 51 */
    }

    setModuleIdentifierString();
}
コード例 #11
0
ファイル: lua_tests.c プロジェクト: mambrus/bitfire
static void 
open_std_libs(lua_State *l) 
{
    luaopen_base(l);   lua_settop(l, 0); 
    luaopen_table(l);  lua_settop(l, 0); 
    luaopen_io(l);     lua_settop(l, 0); 
    luaopen_string(l); lua_settop(l, 0); 
    luaopen_debug(l);  lua_settop(l, 0); 
    luaopen_math(l);   lua_settop(l, 0); 
}
コード例 #12
0
ファイル: lua_iface.cpp プロジェクト: AsKorysti/anura
	void lua_context::init()
	{
		// initialize Lua
		state_.reset(luaL_newstate(), [](lua_State* L) { lua_close(L); });

		// load various Lua libraries
		luaopen_base(context_ptr());
		luaopen_string(context_ptr());
		luaopen_table(context_ptr());
		luaopen_math(context_ptr());
		luaopen_io(context_ptr());
		luaopen_debug(context_ptr());
		luaL_openlibs(context_ptr());

		luaL_newmetatable(context_ptr(), function_str);
		luaL_setfuncs(context_ptr(), gFFLFunctions, 0);	

		luaL_newmetatable(context_ptr(), callable_str);
		luaL_setfuncs(context_ptr(), gCallableFunctions, 0);

		luaL_newmetatable(context_ptr(), callable_function_str);
		luaL_setfuncs(context_ptr(), gFFLCallableFunctions, 0);

		luaL_newmetatable(context_ptr(), lib_functions_str);
		luaL_setfuncs(context_ptr(), gLibMetaFunctions, 0);

		push_anura_table(context_ptr());

		/*dostring(
			"local lvl = Anura.level()\n"
			"print(lvl.id, lvl.music_volume, lvl.in_editor)\n"
			"Anura.debug('abcd')\n"
			"Anura.eval('debug(map(range(10),value))')\n"
			"local camera = lvl.camera\n"
			"print('Camera speed: ' .. camera.speed)\n"
			"for n = 1, 10 do\n"
			"  camera.speed = n\n"
			"  print('Camera speed: ' .. camera.speed)\n"
			"end\n"
			"lvl.player:debug_rect(lvl.player.mid_x-50, lvl.player.mid_y-50, 100, 100)\n"
			//"for i,v in ipairs(lvl.active_chars) do\n"
			//"for i,v in ipairs(Anura.eval('range(10)')) do\n"
			"local mm = Anura.eval('{q(a):1,q(b):2}')\n"
			//"print(mm.a)\n"
			"for i,v in pairs(mm) do\n"
			"  print(i, v)\n"
			"end\n"
		);*/

		/*dostring("local me = Anura.me\n"
			"print(me.speed)",
			level::current().camera().get()
		);*/
	}
コード例 #13
0
ファイル: interp.c プロジェクト: sebcat/birk
interp_t *interp_new(int flags, int ipcfd) {
	interp_t *interp = NULL;
	lua_State *L = NULL;
	static const luaL_Reg ipcfuncs[] = {
		{"ready", bipc_ready},
		{"connect", bipc_connect},
		{NULL, NULL},
	};

	L = luaL_newstate();
	if (L == NULL) {
		return NULL;
	}

	luaopen_base(L);
	luaopen_coroutine(L);
	luaopen_table(L);
	luaopen_string(L);
#if (LUA_VERSION_NUM >= 503)
	luaopen_utf8(L);
#endif
	luaopen_bit32(L);
	luaopen_math(L);
	luaopen_debug(L);
	luaopen_package(L);
	/* not opened: io, os */

	/* create a userdata object that represents the interpreter */
	interp = (interp_t*)lua_newuserdata(L, sizeof(interp_t));
	if (interp == NULL) {
		lua_close(L);
		return NULL;
	}

	memset(interp, 0, sizeof(interp_t));
	interp->ipcfd = ipcfd;
	interp->L = L;

	/* Build a metatable with the methods for our userdata object.
	 * Assign the userdata object to BIRK_IPCNAME */
	luaL_newmetatable(L, BIRK_IPCNAME);
	lua_pushvalue(L, -1);
	lua_setfield(L, -2, "__index");
	luaL_setfuncs(L, ipcfuncs, 0);
	lua_setmetatable(L, -2);
	lua_setglobal(L, BIRK_IPCNAME);

	if ((flags & INTERPF_LOADBIRK) && interp_load(interp, "birk") != BIRK_OK) {
		/* error message is set, caller should check it on return */
		return interp;
	}

	return interp;
}
コード例 #14
0
ファイル: cLua.cpp プロジェクト: andycai/kodeclua
cLua::cLua()
{
	m_pErrorHandler = NULL;

	m_pScriptContext = lua_open();
	luaopen_base(m_pScriptContext);
	luaopen_io(m_pScriptContext);
	luaopen_string(m_pScriptContext);
	luaopen_math(m_pScriptContext);
	luaopen_debug(m_pScriptContext);
	luaopen_table(m_pScriptContext);
}
コード例 #15
0
ファイル: LuaHandle.cpp プロジェクト: Dmytry/spring
CLuaHandle::CLuaHandle(const string& _name, int _order, bool _userMode)
: CEventClient(_name, _order, false), // FIXME
  userMode   (_userMode),
  killMe     (false),
  synced     (false),
#ifdef DEBUG
  printTracebacks(true),
#else
  printTracebacks(false),
#endif
  callinErrors(0)
{
	L = lua_open();
	luaopen_debug(L);
}
コード例 #16
0
ファイル: LuaManager.cpp プロジェクト: JunC74/PYX
void LuaManager::Init()
{
	luaState = lua_open();
	assert(luaState);

	luaopen_base (luaState);
	luaopen_table (luaState);
	luaopen_string (luaState);
	luaopen_math (luaState);
	luaopen_debug (luaState);
	luaL_openlibs(luaState);
	toluafix_open(luaState);
	tolua_attempt_open(luaState);
	SetLuaLoaderFunc(LuaLoader);
	LuaOpenLibName();
}
コード例 #17
0
ファイル: luainpython.c プロジェクト: mctoyama/dice
initlua(void)
{
	PyObject *m;
	m = Py_InitModule("lua", lua_methods);

	if (!L) {
		L = lua_open();
		luaopen_base(L);
		luaopen_table(L);
		luaopen_io(L);
		luaopen_string(L);
		luaopen_debug(L);
		luaopen_loadlib(L);
		luaopen_python(L);
		lua_settop(L, 0);
	}
}
コード例 #18
0
ファイル: LuaTcpConsole.cpp プロジェクト: jmckaskill/qsmp
LuaTcpSocket::LuaTcpSocket(QTcpSocket* socket,boost::function<void ()> disconnect_callback)
: socket_(socket),
  lua_(lua_open()),
  disconnect_callback_(disconnect_callback)
{
  connect(socket_.get(),SIGNAL(readyRead()),SLOT(onReadyRead()));
  connect(socket_.get(),SIGNAL(disconnected()),SLOT(onDisconnect()));

  luaopen_base(lua_);
  luaopen_table(lua_);
  luaopen_string(lua_);
  luaopen_math(lua_);
  luaopen_debug(lua_);
  setSocket(lua_,this);
  lua_register(lua_,"print",&LuaTcpSocket_Print);
  lua_register(lua_,"raw_input",&LuaTcpSocket_RawInput);
}
コード例 #19
0
ファイル: scriptman.cpp プロジェクト: Supermanu/xoreos
void ScriptManager::openLuaState() {
	_luaState = lua_open();
	if (!_luaState) {
		throw Common::Exception("Failed to open Lua state");
	}

	luaopen_base(_luaState);
	luaopen_io(_luaState);
	luaopen_math(_luaState);
	luaopen_string(_luaState);
	luaopen_table(_luaState);
	luaopen_loadlib(_luaState);
	luaopen_debug(_luaState);

	tolua_open(_luaState);

	lua_atpanic(_luaState, &ScriptManager::atPanic);
}
コード例 #20
0
ファイル: CLuaMain.cpp プロジェクト: Gothem/mtasa-blue
void CLuaMain::InitVM ( void )
{
    assert( !m_luaVM );

    // Create a new VM
    m_luaVM = lua_open ();
    m_pLuaManager->OnLuaMainOpenVM( this, m_luaVM );

    // Set the instruction count hook
    lua_sethook ( m_luaVM, InstructionCountHook, LUA_MASKCOUNT, HOOK_INSTRUCTION_COUNT );

    // Load LUA libraries
    luaopen_base ( m_luaVM );
    luaopen_math ( m_luaVM );
    luaopen_string ( m_luaVM );
    luaopen_table ( m_luaVM );
    luaopen_debug ( m_luaVM );
    luaopen_utf8 ( m_luaVM );

    // Initialize security restrictions. Very important to prevent lua trojans and viruses!
    InitSecurity ();

    // Registering C functions
    CLuaCFunctions::RegisterFunctionsWithVM ( m_luaVM );

    // Create class metatables
    InitClasses ( m_luaVM );

    // Oli: Don't forget to add new ones to CLuaManager::LoadCFunctions. Thanks!

    // create global vars
    lua_pushelement ( m_luaVM, g_pGame->GetMapManager()->GetRootElement() );
    lua_setglobal ( m_luaVM, "root" );

    lua_pushresource ( m_luaVM, m_pResource );
    lua_setglobal ( m_luaVM, "resource" );

    lua_pushelement ( m_luaVM, m_pResource->GetResourceRootElement () );
    lua_setglobal ( m_luaVM, "resourceRoot" );

    // Load pre-loaded lua code
    LoadScript ( szPreloadedScript );
}
コード例 #21
0
ファイル: LuaBridge.cpp プロジェクト: 0xmono/miranda-ng
CLuaBridge::CLuaBridge(void) : m_pLuaContext(NULL)
{
	m_pLuaContext = lua_open();

	if (m_pLuaContext != NULL)
	{
		lua_pushcclosure(m_pLuaContext, LuaDebugMessage, 0);
		lua_setglobal(m_pLuaContext, "trace");

		lua_atpanic(m_pLuaContext, (lua_CFunction)HandleLuaAsssert);

		luaopen_io(m_pLuaContext);
		luaopen_math(m_pLuaContext);
		luaopen_base(m_pLuaContext);
		luaopen_loadlib(m_pLuaContext);
		luaopen_table(m_pLuaContext);
		luaopen_string(m_pLuaContext);
		luaopen_debug(m_pLuaContext);		
	}
}
コード例 #22
0
ファイル: modules.c プロジェクト: BigJoe02/rumble
/*
 =======================================================================================================================
 =======================================================================================================================
 */
void rumble_modules_load(masterHandle *master) {

    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    rumbleKeyValuePair  *el;
    dvector_element     *line;
    uint32_t            ver;
    int                 x;
#ifdef _WIN32
    HINSTANCE           handle;
#else
    void                *handle;
#endif
    rumbleModInit       init;
    rumbleVerCheck      mcheck;
    rumble_module_info  *modinfo;
    rumbleService       *svc;
    char                *error = 0;
    const char          *services[] = { "mailman", "smtp", "pop3", "imap4", 0 };
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    rumble_debug(NULL, "core", "Preparing to load modules");
    for (x = 0; services[x]; x++) {
        svc = comm_serviceHandle(services[x]);
        if (svc) {
            rumble_debug(NULL, "core", "Flushing hook structs for %s", services[x]);
            svc->cue_hooks = cvector_init();
            svc->init_hooks = cvector_init();
            svc->exit_hooks = cvector_init();
        }
    }

    rumble_debug(NULL, "core", "Loading modules");
    for (line = master->_core.conf->first; line != NULL; line = line->next) {
        el = (rumbleKeyValuePair *) line->object;
        if (!strcmp(el->key, "loadmodule"))
        {
#if R_WINDOWS
            handle = LoadLibraryA(el->value);
#else
            handle = dlopen(el->value, RTLD_LAZY | RTLD_NODELETE);
            error = dlerror();
#endif
            if (!handle) {
                error = error ? error : "(no such file?)";
                fprintf(stderr, "\nError loading %s: %s\n", el->value, error);
                rumble_debug(NULL, "core", "Error loading %s: %s", el->value, error);
                exit(1);
            }

            if (error) {
                rumble_debug(NULL, "core", "Warning: %s\n", error);
            }

            modinfo = (rumble_module_info *) calloc(1, sizeof(rumble_module_info));
            if (!modinfo) merror();
            modinfo->author = 0;
            modinfo->description = 0;
            modinfo->title = 0;
            init = (rumbleModInit) dlsym(handle, "rumble_module_init");
            mcheck = (rumbleVerCheck) dlsym(handle, "rumble_module_check");
            modinfo->config = (rumbleModConfig) dlsym(handle, "rumble_module_config");
            error = (init == 0 || mcheck == 0) ? "no errors" : 0;
            if (error != NULL) {
                rumble_debug(NULL, "core", "Warning: %s does not contain required module functions.\n", el->value);
            }

            if (init && mcheck) {
                master->_core.currentSO = el->value;
                dvector_add(master->_core.modules, modinfo);
                ver = (*mcheck) ();
                ver = (ver & 0xFFFFFF00) + (RUMBLE_VERSION & 0x000000FF);
                x = EXIT_SUCCESS;
                if (ver > RUMBLE_VERSION || ver < RUMBLE_VERSION_REQUIRED) {
                    if (ver > RUMBLE_VERSION) {
                        rumble_debug(NULL, "module",
                                     "Error: %s was compiled with a newer version of librumble (v%#X) than this server executable (v%#X).\nPlease recompile the module using the latest sources to avoid crashes or bugs.\n",
                                 el->value, ver, RUMBLE_VERSION);
                    } else {
                        rumble_debug(NULL, "module",
                                     "Error: %s was compiled with an older version of librumble (v%#X).\nPlease recompile the module using the latest sources (v%#X) to avoid crashes or bugs.\n",
                                 el->value, ver, RUMBLE_VERSION);
                    }
                } else {
                    modinfo->file = el->value;
                    x = init(master, modinfo);
                }

                if (x != EXIT_SUCCESS) {
                    rumble_debug(NULL, "module", "Error: %s failed to load!", el->value);
                    dlclose(handle);
                }

                if (x == EXIT_SUCCESS) {
                    if (modinfo->title) rumble_debug(NULL, "module", "Loaded extension: %-30s", modinfo->title);
                    else rumble_debug(NULL, "module", "Loaded %48s", el->value);
                } else rumble_debug(NULL, "module", "%s exited prematurely!", el->value);
            }

            /*
             * dlclose(handle);
             */
        }

#ifdef RUMBLE_LUA
        else if (!strcmp(el->key, "loadscript")) {

            /*~~~~~~~~~~~*/
            int         x;
            lua_State   *L;
            /*~~~~~~~~~~~*/

            for (x = 0; x < RUMBLE_LSTATES; x++) {
                if (!master->lua.states[x].state) {
                    master->lua.states[x].state = luaL_newstate();
                    L = (lua_State *) master->lua.states[x].state;
                    lua_pushinteger(L, x);
                    luaL_ref(L, LUA_REGISTRYINDEX);
                    luaL_openlibs(L);
                    luaopen_debug(L);
                    Foo_register(L);
                }
            }

            printf("Loading script <%s>\n", el->value);

            /* Load the file into all states */
            for (x = 0; x < RUMBLE_LSTATES; x++) {
                L = (lua_State *) master->lua.states[x].state;
                if (luaL_loadfile(L, el->value)) {
                    rumble_debug(NULL, "lua", "Couldn't load script: %s", lua_tostring(L, -1));
                    break;
                } else if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
                    rumble_debug(NULL, "lua", "Failed to run <%s>: %s\n", el->value, lua_tostring(L, -1));
                    break;
                }
            }
        }
#endif
    }
}
コード例 #23
0
ファイル: tolua.c プロジェクト: madhatternc/mangos2
int main (int argc, char* argv[])
{
 lua_State* L = lua_open();
    luaopen_base(L);
    luaopen_io(L);
    luaopen_string(L);
    luaopen_table(L);
    luaopen_math(L);
    luaopen_debug(L);

 lua_pushstring(L,TOLUA_VERSION); lua_setglobal(L,"TOLUA_VERSION");

 if (argc==1)
 {
  help();
  return 0;
 }
 else
 {
  int i, t;
  lua_newtable(L);
  lua_pushvalue(L,-1);
  lua_setglobal(L,"flags");
  t = lua_gettop(L);
  for (i=1; i<argc; ++i)
  {
   if (*argv[i] == '-')
   {
    switch (argv[i][1])
    {
     case 'v': version(); return 0;
     case 'h': help(); return 0;
     case 'p': setfield(L,t,"p",""); break;
     case 'P': setfield(L,t,"P",""); break;
     case 'o': setfield(L,t,"o",argv[++i]); break;
     case 'n': setfield(L,t,"n",argv[++i]); break;
     case 'H': setfield(L,t,"H",argv[++i]); break;
     case 'S': setfield(L,t,"S",""); break;
     case '1': setfield(L,t,"1",""); break;
     case 'L': setfield(L,t,"L",argv[++i]); break;
     default: error(argv[i]); break;
    }
   }
   else
   {
    setfield(L,t,"f",argv[i]);
    break;
   }
  }
  lua_pop(L,1);
 }
/* #define TOLUA_SCRIPT_RUN */
#ifndef TOLUA_SCRIPT_RUN
 {
  int tolua_tolua_open (lua_State* L);
  tolua_tolua_open(L);
 }
#else
 {
  char* p;
  char  path[BUFSIZ];
  strcpy(path,argv[0]);
  p = strrchr(path,'/');
  if (p==NULL) p = strrchr(path,'\\');
  p = (p==NULL) ? path : p+1;
  sprintf(p,"%s","../src/bin/lua/");
  lua_pushstring(L,path); lua_setglobal(L,"path");
        strcat(path,"all.lua");
  lua_dofile(L,path);
 }
#endif
 return 0;
}
コード例 #24
0
ファイル: LuaWrapper.cpp プロジェクト: xzben/luaForCpp
bool LuaWrapper::openDebug()		{ luaopen_debug(m_luaState);		return true; }
コード例 #25
0
	void PolycodePlayer::runFile(String fileName) {
		
		Logger::log("Running %s\n", fileName.c_str());
		
		L=lua_open();
		
		luaL_openlibs(L);		
		luaopen_debug(L);		
		luaopen_Polycode(L);
				
		lua_getfield(L, LUA_GLOBALSINDEX, "package");	// push "package"
		lua_getfield(L, -1, "loaders");					// push "package.loaders"
		lua_remove(L, -2);								// remove "package"
		
		// Count the number of entries in package.loaders.
		// Table is now at index -2, since 'nil' is right on top of it.
		// lua_next pushes a key and a value onto the stack.
		int numLoaders = 0;
		lua_pushnil(L);
		while (lua_next(L, -2) != 0) 
		{
			lua_pop(L, 1);
			numLoaders++;
		}
		
		lua_pushinteger(L, numLoaders + 1);
		lua_pushcfunction(L, MyLoader);
		lua_rawset(L, -3);
		
		// Table is still on the stack.  Get rid of it now.
		lua_pop(L, 1);		
		
		lua_register(L, "debugPrint", debugPrint);
		lua_register(L, "__customError", customError);					

		lua_register(L, "__are_same_c_class", areSameCClass);
		
		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "class");		
		lua_call(L, 1, 0);

		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "Polycode");		
		lua_call(L, 1, 0);		

		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "Physics2D");		
		lua_call(L, 1, 0);		

		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "Physics3D");		
		lua_call(L, 1, 0);		

		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "UI");		
		lua_call(L, 1, 0);		
		
		lua_getfield(L, LUA_GLOBALSINDEX, "require");
		lua_pushstring(L, "defaults");		
		lua_call(L, 1, 0);
		
		luaopen_Physics2D(L);
		luaopen_Physics3D(L);
		luaopen_UI(L);
		
				
		/*		
		for(int i=0; i < loadedModules.size(); i++) {
			String moduleName = loadedModules[i];
#ifdef _WINDOWS
			TCHAR _tempPath[4098];
			TCHAR tempPath[4098];
			GetTempPathW(4098, _tempPath);
			GetLongPathNameW(_tempPath, tempPath, 4098);
			String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
#else

	#if defined(__APPLE__) && defined(__MACH__)
			String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
	#else
			String moduleDestPath = String("/tmp/") + moduleName+ String(".so");
	#endif
#endif
			String moduleLoadCall = String("luaopen_") + moduleName;
			lua_getfield(L, LUA_GLOBALSINDEX, "require");
			lua_pushstring(L, moduleName.c_str());		
			lua_call(L, 1, 0);

			printf("LOADING MODULE %s\n", moduleDestPath.c_str());
			lua_getfield(L, LUA_GLOBALSINDEX, "package");
			lua_getfield(L, -1, "loadlib");	
			lua_pushstring(L, moduleDestPath.c_str());
			lua_pushstring(L, moduleLoadCall.c_str());			
			lua_call(L, 2, 2);
			
			lua_setfield(L, LUA_GLOBALSINDEX, "err");								
			lua_setfield(L, LUA_GLOBALSINDEX, "f");		

//			lua_getfield(L, LUA_GLOBALSINDEX, "print");
//			lua_getfield(L, LUA_GLOBALSINDEX, "err");						
//			lua_call(L, 1, 0);						

			printf("SETTING CORE SERVICES\n");			
			lua_getfield(L, LUA_GLOBALSINDEX, "f");
			lua_getfield(L, LUA_GLOBALSINDEX, "__core__services__instance");						
			lua_call(L, 1, 0);			
			
			printf("DONE LOADING MODULE...\n");				
			//local f = package.loadlib("/Users/ivansafrin/Desktop/Workshop/HelloPolycodeLUA/libPolycode2DPhysicsModule.dylib", "luaopen_Physics2D")
			//f(Polycore.CoreServices_getInstance())
					
		}
*/
		String fileData = "";

		OSFILE *inFile = OSBasics::open(fileName, "r");	
		if(inFile) {
			Logger::log("Opened entrypoint file...");
			OSBasics::seek(inFile, 0, SEEK_END);	
			long progsize = OSBasics::tell(inFile);
			OSBasics::seek(inFile, 0, SEEK_SET);
			char *buffer = (char*)malloc(progsize+1);
			memset(buffer, 0, progsize+1);
			OSBasics::read(buffer, progsize, 1, inFile);
			fileData = String(buffer);		
			free(buffer);
			OSBasics::close(inFile);	
		} else {
			Logger::log("Error opening entrypoint file (%s)\n", fileName.c_str());
		}
		
				
		String fullScript = fileData;
		
		doneLoading = true;
		
		//lua_gc(L, LUA_GCSTOP, 0);
		
		

		lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
		errH = lua_gettop(L);

		//CoreServices::getInstance()->getCore()->lockMutex(CoreServices::getRenderMutex());			
		if (report(L, luaL_loadstring(L, fullScript.c_str()))) {			
			//CoreServices::getInstance()->getCore()->unlockMutex(CoreServices::getRenderMutex());			
			Logger::log("CRASH LOADING SCRIPT FILE\n");
//			exit(1);				
		} else {
		
		
			if (lua_pcall(L, 0,0,errH)) {
				Logger::log("CRASH EXECUTING FILE\n");
			}
		}
	}
コード例 #26
0
ファイル: lsLuaState.cpp プロジェクト: Bewolf2/LoomSDK
void LSLuaState::open()
{
    assert(!L);

    L = lua_newstate(lsLuaAlloc, NULL);
    //L = lua_open();
    toLuaState.insert(L, this);

    luaopen_base(L);
    luaopen_table(L);
    luaopen_string(L);
    luaopen_math(L);
    luaL_openlibs(L);

    // open the lua debug library
    luaopen_debug(L);

    // open socket library
    luaopen_socket_core(L);

    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXCLASSES);

    lua_newtable(L);
    lua_setglobal(L, "__ls_nativeclasses");

    lua_pushcfunction(L, traceback);
    lua_setglobal(L, "__ls_traceback");
    _tracemessage[0] = 0;

    // entry -> version
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDVERSION);

    // entry -> native user data
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDUSERDATA);

    // native user data -> script instance
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDNATIVESCRIPT);

    // native delegate table
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXNATIVEDELEGATES);

    // interned field name lookup
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXMEMBERINFONAME);

    // typeid -> type*
    lua_newtable(L);
    lua_rawseti(L, LUA_GLOBALSINDEX, LSASSEMBLYLOOKUP);

    // lua/luacfunction -> MethodBase* lookups
    lua_newtable(L);

    // weak key metatable
    lua_newtable(L);
    lua_pushstring(L, "k");
    lua_setfield(L, -2, "__mode");
    lua_setmetatable(L, -2);

    lua_rawseti(L, LUA_GLOBALSINDEX, LSINDEXMETHODLOOKUP);

    lsr_instanceregister(L);

    NativeInterface::registerNativeTypes(L);
}
コード例 #27
0
ファイル: weechat-lua.c プロジェクト: jameslord/weechat
int
weechat_lua_load (const char *filename)
{
    FILE *fp;
    char *weechat_lua_code = {
        "weechat_outputs = {\n"
        "    write = function (self, str)\n"
        "        weechat.print(\"\", \"lua: stdout/stderr: \" .. str)\n"
        "    end\n"
        "}\n"
        "io.stdout = weechat_outputs\n"
        "io.stderr = weechat_outputs\n"
    };

    if ((fp = fopen (filename, "r")) == NULL)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: script \"%s\" not found"),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME, filename);
        return 0;
    }

    if ((weechat_lua_plugin->debug >= 2) || !lua_quiet)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s: loading script \"%s\""),
                        LUA_PLUGIN_NAME, filename);
    }

    lua_current_script = NULL;
    lua_registered_script = NULL;

    lua_current_interpreter = luaL_newstate();

    if (lua_current_interpreter == NULL)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to create new "
                                         "sub-interpreter"),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME);
        fclose (fp);
        return 0;
    }

#ifdef LUA_VERSION_NUM /* LUA_VERSION_NUM is defined only in lua >= 5.1.0 */
    luaL_openlibs (lua_current_interpreter);
#else
    luaopen_base (lua_current_interpreter);
    luaopen_string (lua_current_interpreter);
    luaopen_table (lua_current_interpreter);
    luaopen_math (lua_current_interpreter);
    luaopen_io (lua_current_interpreter);
    luaopen_debug (lua_current_interpreter);
#endif

    weechat_lua_register_lib (lua_current_interpreter, "weechat", weechat_lua_api_funcs);

#ifdef LUA_VERSION_NUM
    if (luaL_dostring (lua_current_interpreter, weechat_lua_code) != 0)
#else
    if (lua_dostring (lua_current_interpreter, weechat_lua_code) != 0)
#endif
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to redirect stdout "
                                         "and stderr"),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME);
    }

    lua_current_script_filename = filename;

    if (luaL_loadfile (lua_current_interpreter, filename) != 0)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to load file \"%s\""),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME, filename);
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: error: %s"),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME,
                        lua_tostring (lua_current_interpreter, -1));
        lua_close (lua_current_interpreter);
        fclose (fp);
        return 0;
    }

    if (lua_pcall (lua_current_interpreter, 0, 0, 0) != 0)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to execute file "
                                         "\"%s\""),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME, filename);
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: error: %s"),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME,
                        lua_tostring (lua_current_interpreter, -1));
        lua_close (lua_current_interpreter);
        fclose (fp);

        /* if script was registered, remove it from list */
        if (lua_current_script)
        {
            plugin_script_remove (weechat_lua_plugin, &lua_scripts, &last_lua_script,
                                  lua_current_script);
        }

        return 0;
    }
    fclose (fp);

    if (!lua_registered_script)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: function \"register\" not "
                                         "found (or failed) in file \"%s\""),
                        weechat_prefix ("error"), LUA_PLUGIN_NAME, filename);
        lua_close (lua_current_interpreter);
        return 0;
    }
    lua_current_script = lua_registered_script;

    lua_current_script->interpreter = (lua_State *) lua_current_interpreter;

    /*
     * set input/close callbacks for buffers created by this script
     * (to restore callbacks after upgrade)
     */
    plugin_script_set_buffer_callbacks (weechat_lua_plugin,
                                        lua_scripts,
                                        lua_current_script,
                                        &weechat_lua_api_buffer_input_data_cb,
                                        &weechat_lua_api_buffer_close_cb);

    weechat_hook_signal_send ("lua_script_loaded", WEECHAT_HOOK_SIGNAL_STRING,
                              lua_current_script->filename);

    return 1;
}
コード例 #28
0
/**
 * @version 05/06/08	Bang2ni - __get_guildid_byname 스크립트 함수 등록
 */
bool CQuestManager::InitializeLua()
{
#if LUA_V == 503
    L = lua_open();

    luaopen_base(L);
    luaopen_table(L);
    luaopen_string(L);
    luaopen_math(L);
    //TEMP
    luaopen_io(L);
    luaopen_debug(L);
#elif LUA_V == 523
    L = luaL_newstate();

    luaL_openlibs(L);
    //luaopen_debug(L);
#else
#error "lua version not found"
#endif

    RegisterAffectFunctionTable();
    RegisterBuildingFunctionTable();
    RegisterDungeonFunctionTable();
    RegisterGameFunctionTable();
    RegisterGuildFunctionTable();
    RegisterHorseFunctionTable();
#ifdef __PET_SYSTEM__
    RegisterPetFunctionTable();
#endif
    RegisterITEMFunctionTable();
    RegisterMarriageFunctionTable();
    RegisterNPCFunctionTable();
    RegisterPartyFunctionTable();
    RegisterPCFunctionTable();
    RegisterQuestFunctionTable();
    RegisterTargetFunctionTable();
    RegisterArenaFunctionTable();
    RegisterForkedFunctionTable();
    RegisterMonarchFunctionTable();
    RegisterOXEventFunctionTable();
    RegisterMgmtFunctionTable();
    RegisterBattleArenaFunctionTable();
    RegisterDanceEventFunctionTable();
    RegisterDragonLairFunctionTable();
    RegisterSpeedServerFunctionTable();
    RegisterDragonSoulFunctionTable();

    {
        luaL_reg member_functions[] =
        {
            { "chat",			member_chat		},
            { "set_ready",			member_set_ready	},
            { "clear_ready",		member_clear_ready	},
            { NULL,				NULL			}
        };

        AddLuaFunctionTable("member", member_functions);
    }

    {
        luaL_reg highscore_functions[] =
        {
            { "register",			highscore_register	},
            { "show",			highscore_show		},
            { NULL,				NULL			}
        };

        AddLuaFunctionTable("highscore", highscore_functions);
    }

    {
        luaL_reg mob_functions[] =
        {
            { "spawn",			mob_spawn		},
            { "spawn_group",		mob_spawn_group		},
            { NULL,				NULL			}
        };

        AddLuaFunctionTable("mob", mob_functions);
    }

    //
    // global namespace functions
    //
    RegisterGlobalFunctionTable(L);

    // LUA_INIT_ERROR_MESSAGE
    {
        char settingsFileName[256];
        snprintf(settingsFileName, sizeof(settingsFileName), "%s/settings.lua", LocaleService_GetBasePath().c_str());

        int settingsLoadingResult = lua_dofile(L, settingsFileName);
        sys_log(0, "LoadSettings(%s), returns %d", settingsFileName, settingsLoadingResult);
        if (settingsLoadingResult != 0)
        {
            sys_err("LOAD_SETTINS_FAILURE(%s)", settingsFileName);
            return false;
        }
    }

    {
        char questlibFileName[256];
        snprintf(questlibFileName, sizeof(questlibFileName), "%s/questlib.lua", LocaleService_GetQuestPath().c_str());

        int questlibLoadingResult = lua_dofile(L, questlibFileName);
        sys_log(0, "LoadQuestlib(%s), returns %d", questlibFileName, questlibLoadingResult);
        if (questlibLoadingResult != 0)
        {
            sys_err("LOAD_QUESTLIB_FAILURE(%s)", questlibFileName);
            return false;
        }
    }

    if (LC_IsEurope())
    {
        char translateFileName[256];
        snprintf(translateFileName, sizeof(translateFileName), "%s/translate.lua", LocaleService_GetBasePath().c_str());

        int translateLoadingResult = lua_dofile(L, translateFileName);
        sys_log(0, "LoadTranslate(%s), returns %d", translateFileName, translateLoadingResult);
        if (translateLoadingResult != 0)
        {
            sys_err("LOAD_TRANSLATE_ERROR(%s)", translateFileName);
            return false;
        }
    }

    {
        char questLocaleFileName[256];
        if (LC_IsEurope())
        {
            snprintf(questLocaleFileName, sizeof(questLocaleFileName), "%s/locale.lua", g_stQuestDir.c_str());
        }
        else
        {
            snprintf(questLocaleFileName, sizeof(questLocaleFileName), "%s/locale_%s.lua", g_stQuestDir.c_str(), g_stLocale.c_str());
        }

        int questLocaleLoadingResult = lua_dofile(L, questLocaleFileName);
        sys_log(0, "LoadQuestLocale(%s), returns %d", questLocaleFileName, questLocaleLoadingResult);
        if (questLocaleLoadingResult != 0)
        {
            sys_err("LoadQuestLocale(%s) FAILURE", questLocaleFileName);
            return false;
        }
    }
    // END_OF_LUA_INIT_ERROR_MESSAGE

    for (itertype(g_setQuestObjectDir) it = g_setQuestObjectDir.begin(); it != g_setQuestObjectDir.end(); ++it)
    {
        const string& stQuestObjectDir = *it;
        char buf[PATH_MAX];
        snprintf(buf, sizeof(buf), "%s/state/", stQuestObjectDir.c_str());
        DIR * pdir = opendir(buf);
        int iQuestIdx = 0;

        if (pdir)
        {
            dirent * pde;

            while ((pde = readdir(pdir)))
            {
                if (pde->d_name[0] == '.')
                    continue;

                snprintf(buf + 11, sizeof(buf) - 11, "%s", pde->d_name);

                RegisterQuest(pde->d_name, ++iQuestIdx);
                int ret = lua_dofile(L, (stQuestObjectDir + "/state/" + pde->d_name).c_str());
                sys_log(0, "QUEST: loading %s, returns %d", (stQuestObjectDir + "/state/" + pde->d_name).c_str(), ret);

                BuildStateIndexToName(pde->d_name);
            }

            closedir(pdir);
        }
    }

#if LUA_V == 503
    lua_setgcthreshold(L, 0);
#endif
    lua_newtable(L);
    lua_setglobal(L, "__codecache");
    return true;
}