示例#1
8
bool GameChat::handle_special_commands(GameState* gs,
		const std::string& command) {
	ChatMessage printed;
	const char* content;
	PlayerInst* p = gs->local_player();

	//Spawn monster
	if (starts_with(command, "!spawn ", &content)) {
		const char* rest = content;
		int amnt = strtol(content, (char**)&rest, 10);
		if (content == rest)
			amnt = 1;
		rest = skip_whitespace(rest);

		int enemy = get_enemy_by_name(rest, false);
		if (enemy == -1) {
			printed.message = "No such monster, '" + std::string(rest) + "'!";
			printed.message_colour = Colour(255, 50, 50);
		} else {
			printed.message = std::string(rest) + " has spawned !";
			generate_enemy_after_level_creation(gs, enemy, amnt);
			printed.message_colour = Colour(50, 255, 50);
		}
		add_message(printed);
		return true;
	}

	//Set game speed
	if (starts_with(command, "!gamespeed ", &content)) {
		int gamespeed = squish(atoi(content), 1, 200);
		gs->game_settings().time_per_step = gamespeed;
		printed.message = std::string("Game speed set.");
		printed.message_colour = Colour(50, 255, 50);
		add_message(printed);
		return true;
	}

	//Gain XP
	if (starts_with(command, "!gainxp ", &content)) {
		int xp = atoi(content);
		if (xp > 0 && xp < 999999) {
			printed.message = std::string("You have gained ") + content
					+ " experience.";
			printed.message_colour = Colour(50, 255, 50);
			add_message(printed);
			p->gain_xp(gs, xp);
		} else {
			printed.message = "Invalid experience amount!";
			printed.message_colour = Colour(255, 50, 50);
			add_message(printed);
		}
		return true;
	}

	//Create item
	if (starts_with(command, "!item ", &content)) {
		const char* rest = content;
		int amnt = strtol(content, (char**)&rest, 10);
		if (content == rest)
			amnt = 1;
		rest = skip_whitespace(rest);

		int item = get_item_by_name(rest, false);
		if (item == -1) {
			printed.message = "No such item, '" + std::string(rest) + "'!";
			printed.message_colour = Colour(255, 50, 50);
		} else {
			printed.message = std::string(rest) + " put in your inventory !";
			p->stats().equipment.inventory.add(Item(item), amnt);
			printed.message_colour = Colour(50, 255, 50);
		}
		add_message(printed);
		return true;
	}

	//Kill all monsters
	if (starts_with(command, "!killall", &content)) {
		MonsterController& mc = gs->monster_controller();
		for (int i = 0; i < mc.monster_ids().size(); i++) {
			EnemyInst* inst = (EnemyInst*)gs->get_instance(mc.monster_ids()[i]);
			if (inst) {
				inst->damage(gs, 99999);
			}
		}
		printed.message = "Killed all monsters.";
		printed.message_colour = Colour(50, 255, 50);
		add_message(printed);
		return true;
	}

	lua_State* L = gs->get_luastate();
	static LuaValue script_globals;
	if (script_globals.empty()) {
		script_globals.table_initialize(L);
//		script_globals.push(L);
//		int script = lua_gettop(L);
//		lua_pushvalue(L, LUA_GLOBALSINDEX);
//		lua_setmetatable(L, script);
//		lua_pop(L, 1);
	}

	lua_push_gameinst(L, p);
	script_globals.table_pop_value(L, "player");
	lua_push_combatstats(L, p);
	script_globals.table_pop_value(L, "stats");

	//Run lua command
	if (starts_with(command, "!lua ", &content)) {
//		std::string luafunc = std::string(content);

		int prior_top = lua_gettop(L);

		luaL_loadstring(L, content);
		if (lua_isstring(L, -1)) {
			const char* val = lua_tostring(L, -1);
			add_message(val, /*iserr ? Colour(255,50,50) :*/
			Colour(120, 120, 255));
			return true;
		}

		int lfunc = lua_gettop(L);
		script_globals.push(L);
		lua_setfenv(L, lfunc);

		bool iserr = (lua_pcall(L, 0, LUA_MULTRET, 0) != 0);

		int current_top = lua_gettop(L);

		for (; prior_top < current_top; prior_top++) {
			if (lua_isstring(L, -1)) {
				const char* val = lua_tostring(L, -1);
				add_message(val,
						iserr ? Colour(255, 50, 50) : Colour(120, 120, 255));
			}
			lua_pop(L, 1);
		}

		return true;
	}
	//Run lua file
	if (starts_with(command, "!luafile ", &content)) {
		int prior_top = lua_gettop(L);

		int err_func = luaL_loadfile(L, content);
		if (err_func) {
			const char* val = lua_tostring(L, -1);
			add_message(val, Colour(120, 120, 255));
			lua_pop(L, 1);
			return true;
		}

		int lfunc = lua_gettop(L);
		script_globals.push(L);
		lua_setfenv(L, lfunc);

		bool err_call = (lua_pcall(L, 0, 0, 0) != 0);
		if (err_call) {
			const char* val = lua_tostring(L, -1);
			add_message(val, Colour(120, 120, 255));
			lua_pop(L, 1);
		}
		return true;
	}

	return false;
}
示例#2
0
static int dofile(lua_State *L, const char *name) {
	int status = luaL_loadfile(L, name);
	if (status == LUA_OK)
		status = docall(L, 0, 0);
	return report(L, status);
}
示例#3
0
int _tmain(int argc, _TCHAR* argv[])
{
	lua_State * l = luaL_newstate() ;        //创建lua运行环境
	if ( l == NULL ) err_return(-1,"luaL_newstat() failed",1); 
	luaL_openlibs(l);

	int ret = 0 ;
	ret = luaL_loadfile(l,"func.lua") ;      //加载lua脚本文件
	if ( ret != 0 ) err_return(-1,"luaL_loadfile failed",1) ;
	ret = lua_pcall(l,0,0,0) ;
	if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(l,-1)) ;

	lua_getglobal(l,"width");              //获取lua中定义的变量
	lua_getglobal(l,"height");
	printf("height:%ld width:%ld\n",lua_tointeger(l,-1),lua_tointeger(l,-2)) ;
	lua_pop(l,2) ;                        //恢复lua的栈

	int a = 11 ;
	int b = 12 ;
	lua_getglobal(l,"sum");               //调用lua中的函数sum
	lua_pushinteger(l,a) ;
	lua_pushinteger(l,b) ;
	ret = lua_pcall(l,2,1,0) ;
	if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(l,-1)) ;
	printf("sum:%d + %d = %ld\n",a,b,lua_tointeger(l,-1)) ;
	lua_pop(l,1) ;

	const char str1[] = "hello" ;
	const char str2[] = "world" ;
	lua_getglobal(l,"mystrcat");          //调用lua中的函数mystrcat
	lua_pushstring(l,str1) ;
	lua_pushstring(l,str2) ;
	ret = lua_pcall(l,2,1,0) ;
	if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(l,-1)) ;
	printf("mystrcat:%s%s = %s\n",str1,str2,lua_tostring(l,-1)) ;
	lua_pop(l,1) ;

	lua_pushcfunction(l,csum) ;         //注册在lua中使用的c函数
	lua_setglobal(l,"csum") ;           //绑定到lua中的名字csum

	lua_getglobal(l,"mysum");           //调用lua中的mysum函数,该函数调用本程序中定义的csum函数实现加法
	lua_pushinteger(l,a) ;
	lua_pushinteger(l,b) ;
	ret = lua_pcall(l,2,1,0) ;
	if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(l,-1)) ;
	printf("mysum:%d + %d = %ld\n",a,b,lua_tointeger(l,-1)) ;
	lua_pop(l,1) ;

	int error;
	char str[100];
	while (fgets(str, 100, stdin))
	{
		int nTop = lua_gettop(l);
		error = luaL_loadbuffer(l, str, strlen(str), "") || lua_pcall(l, 0, 0, 0);

		if (error) {

			fprintf(stderr, "%s\n", lua_tostring(l, -1));

			lua_pop(l, 1);/* pop error message from the stack */

		}

		lua_settop(l, nTop);
	}

	lua_close(l) ;                     //释放lua运行环境

	system("pause");
	return 0;
}
示例#4
0
文件: lua.c 项目: brkpt/jamplus
static int dofile (lua_State *L, const char *name) {
  return dochunk(L, luaL_loadfile(L, name));
}
示例#5
0
文件: main.c 项目: buaazp/zimg
/**
 * @brief load_conf load the conf of zimg
 *
 * @param conf conf name
 *
 * @return 1 for OK and -1 for fail
 */
static int load_conf(const char *conf) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    if (luaL_loadfile(L, conf) || lua_pcall(L, 0, 0, 0)) {
        lua_close(L);
        return -1;
    }

    lua_getglobal(L, "is_daemon"); //stack index: -12
    if (lua_isnumber(L, -1))
        settings.is_daemon = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "ip");
    if (lua_isstring(L, -1))
        str_lcpy(settings.ip, lua_tostring(L, -1), sizeof(settings.ip));
    lua_pop(L, 1);

    lua_getglobal(L, "port");
    if (lua_isnumber(L, -1))
        settings.port = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "thread_num");
    if (lua_isnumber(L, -1))
        settings.num_threads = (int)lua_tonumber(L, -1);         /* N workers */
    lua_pop(L, 1);

    lua_getglobal(L, "backlog_num");
    if (lua_isnumber(L, -1))
        settings.backlog = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "max_keepalives");
    if (lua_isnumber(L, -1))
        settings.max_keepalives = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "retry");
    if (lua_isnumber(L, -1))
        settings.retry = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "system");
    if (lua_isstring(L, -1)) {
        char tmp[128];
        snprintf(tmp, 128, "%s %s", settings.server_name, lua_tostring(L, -1));
        snprintf(settings.server_name, 128, "%s", tmp);
    }
    lua_pop(L, 1);

    lua_getglobal(L, "headers");
    if (lua_isstring(L, -1)) {
        settings.headers = conf_get_headers(lua_tostring(L, -1));
    }
    lua_pop(L, 1);

    lua_getglobal(L, "etag");
    if (lua_isnumber(L, -1))
        settings.etag = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "upload_rule");
    if (lua_isstring(L, -1)) {
        settings.up_access = conf_get_rules(lua_tostring(L, -1));
    }
    lua_pop(L, 1);

    lua_getglobal(L, "download_rule");
    if (lua_isstring(L, -1)) {
        settings.down_access = conf_get_rules(lua_tostring(L, -1));
    }
    lua_pop(L, 1);

    lua_getglobal(L, "admin_rule");
    if (lua_isstring(L, -1)) {
        settings.admin_access = conf_get_rules(lua_tostring(L, -1));
    }
    lua_pop(L, 1);

    lua_getglobal(L, "cache");
    if (lua_isnumber(L, -1))
        settings.cache_on = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "mc_ip");
    if (lua_isstring(L, -1))
        str_lcpy(settings.cache_ip, lua_tostring(L, -1), sizeof(settings.cache_ip));
    lua_pop(L, 1);

    lua_getglobal(L, "mc_port");
    if (lua_isnumber(L, -1))
        settings.cache_port = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "log_level");
    if (lua_isnumber(L, -1))
        settings.log_level = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "log_name"); //stack index: -1
    if (lua_isstring(L, -1))
        str_lcpy(settings.log_name, lua_tostring(L, -1), sizeof(settings.log_name));
    lua_pop(L, 1);

    lua_getglobal(L, "root_path");
    if (lua_isstring(L, -1))
        str_lcpy(settings.root_path, lua_tostring(L, -1), sizeof(settings.root_path));
    lua_pop(L, 1);

    lua_getglobal(L, "admin_path");
    if (lua_isstring(L, -1))
        str_lcpy(settings.admin_path, lua_tostring(L, -1), sizeof(settings.admin_path));
    lua_pop(L, 1);

    lua_getglobal(L, "disable_args");
    if (lua_isnumber(L, -1))
        settings.disable_args = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "disable_type");
    if (lua_isnumber(L, -1))
        settings.disable_type = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "disable_zoom_up");
    if (lua_isnumber(L, -1))
        settings.disable_zoom_up = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "script_name"); //stack index: -1
    if (lua_isstring(L, -1))
        str_lcpy(settings.script_name, lua_tostring(L, -1), sizeof(settings.script_name));
    lua_pop(L, 1);

    lua_getglobal(L, "format");
    if (lua_isstring(L, -1))
        str_lcpy(settings.format, lua_tostring(L, -1), sizeof(settings.format));
    lua_pop(L, 1);

    lua_getglobal(L, "quality");
    if (lua_isnumber(L, -1))
        settings.quality = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "mode");
    if (lua_isnumber(L, -1))
        settings.mode = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    set_callback(settings.mode);

    lua_getglobal(L, "save_new");
    if (lua_isnumber(L, -1))
        settings.save_new = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "max_size");
    if (lua_isnumber(L, -1))
        settings.max_size = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "img_path");
    if (lua_isstring(L, -1))
        str_lcpy(settings.img_path, lua_tostring(L, -1), sizeof(settings.img_path));
    lua_pop(L, 1);

    lua_getglobal(L, "beansdb_ip");
    if (lua_isstring(L, -1))
        str_lcpy(settings.beansdb_ip, lua_tostring(L, -1), sizeof(settings.beansdb_ip));
    lua_pop(L, 1);

    lua_getglobal(L, "beansdb_port");
    if (lua_isnumber(L, -1))
        settings.beansdb_port = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_getglobal(L, "ssdb_ip");
    if (lua_isstring(L, -1))
        str_lcpy(settings.ssdb_ip, lua_tostring(L, -1), sizeof(settings.ssdb_ip));
    lua_pop(L, 1);

    lua_getglobal(L, "ssdb_port");
    if (lua_isnumber(L, -1))
        settings.ssdb_port = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);

    //settings.L = L;
    lua_close(L);

    return 1;
}
示例#6
0
int main (int argc, char *argv[])
{
#ifdef FOR_ONEROBOT
  if (argc != 3)
  {
    fprintf(stderr, "%s 192.168.1.221 4001!\n", argv[0]);
    return -1;
  }
#else
  if (argc != 5)
  {
    fprintf(stderr, "%s 192.168.1.221 4001 payload begin_idx!\n", argv[0]);
    return -1;
  }
#endif

  signal(SIGPIPE ,SIG_IGN);
  signal(SIGINT ,SIG_IGN);

  set_max_fds(1024);

  reactor r;
  if (r.open(10000, 2192) != 0)
  {
    fprintf(stderr, "open failed![%s]\n", strerror(errno));
    return -1;
  }

  if (init_log() != 0)
	{
		fprintf(stderr, "init log err.\n");
		return -1;
	}

  host = argv[1];
  port = ::atoi(argv[2]);
#ifndef FOR_ONEROBOT
  g_total_payload = ::atoi(argv[3]);
  begin_id = ::atoi(argv[4]);
#endif

  srand(time_value::start_time.sec());
  time_util::init();

  robot_connector.open(&r);
#ifndef FOR_ONEROBOT
  r.schedule_timer(new timer(begin_id),
                   time_value(0, 800*1000),
                   time_value(0, 800*1000));
#endif

  if (global_param_cfg::instance()->load_config("../config") != 0)
  {
    fprintf(stderr, "Error: config - load global_param_cfg config failed!\n");
    return -1;
  }
  if (scene_config::instance()->load_config("../config") != 0)
  {
    fprintf(stderr, "Error: config - load scene config failed!\n");
    return -1;
  }
  if (buff_config::instance()->load_config("../config") != 0)
  {
    fprintf(stderr, "Error: config - load buff config failed!\n");
    return -1;
  }
  if (skill_config::instance()->load_config("../config") != 0)
  {
    fprintf(stderr, "Error: config - load skill config failed!\n");
    return -1;
  }
  if (item_config::instance()->load_config("../config") != 0)
  {
    fprintf(stderr, "Error: config - load item config failed!\n");
    return -1;
  }

  L = luaL_newstate();
  luaL_openlibs(L);
#ifdef FOR_LUA
  tolua_player_open(L);
  tolua_lua_istream_open(L);
  if (luaL_loadfile(L, "src/ai_func.lua")
      || lua_pcall(L, 0, 0, 0))
  {
    fprintf(stderr, "load ai_func lua file failed!\n");
    return -1;
  }
  if (luaL_loadfile(L, "src/dispatch_msg.lua")
      || lua_pcall(L, 0, 0, 0))
  {
    fprintf(stderr, "load dispatch_msg lua file failed!\n");
    return -1;
  }
#endif

	s_log->rinfo("=============================begin=================");
	e_log->rinfo("=============================begin=================");

#ifdef FOR_ONEROBOT
  ::signal(SIGABRT, svc_core_signal);
  //::signal(SIGSEGV, svc_core_signal);
  inet_address remote_addr(port, host);
  time_value tv(30, 0);
  char ac_bf[32] = {0};
  login_ncurses::input_account(ac_bf);

  if (robot_connector.connect(new player(ac_bf, ""), remote_addr, &tv) != 0)
  {
    e_log->rinfo("connect world failed!");
    return 0;
  }
#endif

  r.run_reactor_event_loop();

#ifdef FOR_ONEROBOT
  director::instance()->exit();
#endif

  lua_close(L);
  return 0;
}
示例#7
0
LUALIB_API int lua_dofile (lua_State *L, const char *filename) {
  return aux_do(L, luaL_loadfile(L, filename));
}
示例#8
0
文件: main.c 项目: Stary2001/vita-lua
int main()
{
    lua_State *lua = luaL_newstate();
    lua_atpanic(lua, panic);

    // Net init
    sceSysmoduleLoadModule(SCE_SYSMODULE_NET);
    SceNetInitParam netInitParam;
    int size = 1024 * 512;
    netInitParam.memory = malloc(size);
    netInitParam.size = size;
    netInitParam.flags = 0;
    sceNetInit(&netInitParam);

    sceSysmoduleLoadModule(SCE_SYSMODULE_HTTP);
#ifdef DEBUGGER_IP
    debugNetInit(DEBUGGER_IP, DEBUGGER_PORT, DEBUG);
#endif
    sceHttpInit(1024 * 50);

    // Init libs
    debugf("Init libs....\n");
    debugf("vita2d...\n");
    vita2d_init();
    debugf("physfs\n");
    PHYSFS_init(NULL);
    debugf("lualibs\n");
    luaL_openlibs(lua);
    debugf("ffi\n");
    open_ffi(lua);

    lua_pushcfunction(lua, print);
    lua_setglobal(lua, "print");

    /*
    // Display splash
    unsigned int goal = 2*60;
    unsigned int counter = 0;
    vita2d_texture *tex = vita2d_load_PNG_buffer(splash_data);
    SceCtrlData pad;
    memset(&pad, 0, sizeof(pad));
    for (;;) {
        ++counter;
        if (counter >= goal)
            break;
        sceCtrlPeekBufferPositive(0, &pad, 1);
        if (pad.buttons & SCE_CTRL_ANY)
            break;
        vita2d_start_drawing();
        vita2d_clear_screen();
        vita2d_draw_texture(tex, 0, 0);
        vita2d_end_drawing();
        vita2d_swap_buffers();
    }
    */

    debugf("[Lua] Loading app0:/lib/init.lua ...\n");
    if(luaL_loadfile(lua, "app0:/lib/init.lua") == 0)
    {
        if(lua_pcall(lua, 0, 0, 0) != 0)
        {
            debugf("[Lua] init error: %s\n", lua_tostring(lua, -1));
            lua_pop(lua, 1);
        }
    }

    /*debugf("[Lua] Loading app0:/boot.lua ...\n");
    if(luaL_loadfile(lua, "app0:/boot.lua") == 0)
    {
        if(lua_pcall(lua, 0, 0, 0) != 0)
        {
            debugf("[Lua] bootscript err: %s\n", lua_tostring(lua, -1));
            lua_pop(lua, 1);
        }
    }
    else
    {
    debugf("[Lua] bootscript load err: %s\n", lua_tostring(lua, -1));
        lua_pop(lua, 1);
    }*/

    debugf("Deinit. Goodbye.\n");
    sceHttpTerm();
    PHYSFS_deinit();
    vita2d_fini();
    //vita2d_free_texture(tex);

    sceKernelExitProcess(0);
    return 0;
}
int main()
{
	int sudoku_1D[81];
	int* sudoku_2D[9];

	// Generate Sudoku Table

	int row1[9] = { 2, 4, 0, 3, 0, 0, 0, 0, 0 };
	int row2[9] = { 0, 0, 0, 5, 2, 0, 4, 0, 7 };
	int row3[9] = { 0, 0, 0, 0, 4, 6, 0, 0, 8 };

	int row4[9] = { 6, 1, 0, 7, 0, 0, 0, 8, 4 };
	int row5[9] = { 0, 0, 9, 0, 6, 0, 5, 0, 0 };
	int row6[9] = { 7, 3, 0, 0, 0, 5, 0, 6, 1 };

	int row7[9] = { 1, 0, 0, 4, 7, 0, 0, 0, 0 };
	int row8[9] = { 3, 0, 2, 0, 5, 1, 0, 0, 0 };
	int row9[9] = { 0, 0, 0, 0, 0, 2, 0, 1, 9 };

	sudoku_2D[0] = row1;
	sudoku_2D[1] = row2;
	sudoku_2D[2] = row3;

	sudoku_2D[3] = row4;
	sudoku_2D[4] = row5;
	sudoku_2D[5] = row6;

	sudoku_2D[6] = row7;
	sudoku_2D[7] = row8;
	sudoku_2D[8] = row9;

	// Convert to 1D array
	int index = 0;
	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			sudoku_1D[index++] = sudoku_2D[i][j];
		}
	}
	

	lua_State* luaEnv;
	luaEnv = luaL_newstate();
	
	// Load the Lua libraries
	luaL_openlibs(luaEnv);
	
	// Load the lua script (but do NOT run it)
	if (luaL_loadfile(luaEnv, "Sudoku Algorithm.lua"))
	{
		retError(luaEnv, "luaL_loadfile() failed");
	}
	
	// Prime the lua environment
	if (lua_pcall(luaEnv, 0, 0, 0))
	{
		retError(luaEnv, "luaL_pcall() failed");
	}
	
	lua_getglobal(luaEnv, "BeginSolving");
	lua_newtable(luaEnv);
	
	// Add the Sudoku 1D table to the stack for use in Lua
	for (int i = 1; i < sizeof(sudoku_1D) / sizeof(*sudoku_1D) + 1; i++)
	{
		lua_pushinteger(luaEnv, i);
		lua_pushinteger(luaEnv, sudoku_1D[i - 1]);
		lua_settable(luaEnv, -3);
	}

	// Call the Lua function
	if (lua_pcall(luaEnv, 1, 2, 0))
	{
		retError(luaEnv, "luaL_pcall() failed");
	}

	// Retrieve the 1D table from Lua
	lua_pushnil(luaEnv);

	// Retrieve the boolean for if the puzzle was solvable
	lua_next(luaEnv, -2);
	int solved = lua_toboolean(luaEnv, -1);
	lua_pop(luaEnv, 1);

	int value = 0;
	index = 0;
	// Retrieve all table elements in a 1D array
	while (lua_next(luaEnv, -2)) {
		value = (int)lua_tonumber(luaEnv, -1);
		lua_pop(luaEnv, 1);
		index = (int)lua_tonumber(luaEnv, -1);

		sudoku_1D[index - 1] = value;
	}

	// Convert back to a 2D array
	index = 0;
	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			sudoku_2D[i][j] = sudoku_1D[index++];
		}
	}

	// Print the solution
	std::cout << "Solution Solvable: ";
	solved ? std::cout << "true" : std::cout << "false";
	std::cout << std::endl;

	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			std::cout <<sudoku_2D[i][j] << " ";
		}
		std::cout << std::endl;
	}

	lua_close(luaEnv);

	system("pause");
	return 0;
}
示例#10
0
int  LuaAgent::LoadFile(const char* pszFileName)
{
    return luaL_loadfile(luaState,pszFileName);
}
示例#11
0
	//Loads the lua table file, and generates a lua_State with the return'd table at the top of the stack
	lua_State* LoadAssetTable(const std::string &i_path, std::function<void(std::string)> error)
	{
		bool wereThereErrors = false;

		// Create a new Lua state
		lua_State* luaState = luaL_newstate();
		if (!luaState)
		{
			if (error)
				error("Failed to create a new Lua state");
			return nullptr;
		}

		// Load the asset file as a "chunk",
		// meaning there will be a callable function at the top of the stack
		{
			const int luaResult = luaL_loadfile(luaState, i_path.c_str());
			if (luaResult != LUA_OK)
			{
				wereThereErrors = true;
				if (error)
					error(lua_tostring(luaState, -1));
				// Pop the error message
				lua_pop(luaState, 1);
				goto OnExit;
			}
		}
		// Execute the "chunk", which should load the asset
		// into a table at the top of the stack
		{
			const int argumentCount = 0;
			const int returnValueCount = LUA_MULTRET;	// Return _everything_ that the file returns
			const int noMessageHandler = 0;
			const int luaResult = lua_pcall(luaState, argumentCount, returnValueCount, noMessageHandler);
			if (luaResult == LUA_OK)
			{
				// A well-behaved asset file will only return a single value
				const int returnedValueCount = lua_gettop(luaState);
				if (returnedValueCount == 1)
				{
					// A correct asset file _must_ return a table
					if (!lua_istable(luaState, -1))
					{
						wereThereErrors = true;
						if (error)
						{
							std::stringstream errorStream;
							errorStream << "Asset files must return a table (instead of a " << luaL_typename(luaState, -1) << ")";
							error(errorStream.str());
						}
						// Pop the returned non-table value
						lua_pop(luaState, 1);
						goto OnExit;
					}
				}
				else
				{
					wereThereErrors = true;
					if (error)
					{
						std::stringstream errorStream;
						errorStream << "Asset files must return a single table (instead of " << returnedValueCount << " values)";
						error(errorStream.str());
					}
					// Pop every value that was returned
					lua_pop(luaState, returnedValueCount);
					goto OnExit;
				}
			}
			else
			{
				wereThereErrors = true;
				if (error)
					error(lua_tostring(luaState, -1));
				// Pop the error message
				lua_pop(luaState, 1);
				goto OnExit;
			}
		}

		// If this code is reached the asset file was loaded successfully, and its table is now at index -1
		if (lua_istable(luaState, -1))
			return luaState;

		// Pop the table
		lua_pop(luaState, 1);

	OnExit:

		if (luaState)
		{
			// If I haven't made any mistakes
			// there shouldn't be anything on the stack,
			// regardless of any errors encountered while loading the file:
			assert(lua_gettop(luaState) == 0);

			lua_close(luaState);
		}

		return nullptr;
	}
示例#12
0
文件: main.c 项目: glankk/n64
int main(int argc, char *argv[])
{
  if (argc > 1) {
    /* lua initialization */
    lua_State *L = luaL_newstate();
    if (!L) {
      puts("failed to create lua state");
      return LUA_ERRMEM;
    }
    luaL_requiref(L, "_G", luaopen_base, 1);
    luaL_requiref(L, "package", luaopen_package, 1);
    luaL_requiref(L, "coroutine", luaopen_coroutine, 1);
    luaL_requiref(L, "string", luaopen_string, 1);
    luaL_requiref(L, "utf8", luaopen_utf8, 1);
    luaL_requiref(L, "table", luaopen_table, 1);
    luaL_requiref(L, "math", luaopen_math, 1);
    luaL_requiref(L, "io", luaopen_io, 1);
    luaL_requiref(L, "os", luaopen_os, 1);
    lua_settop(L, 0);
    /* main interface object initialization */
    lgru_gru_create(L);
    lua_setglobal(L, "gru");
    /* script execution */
    int is_builtin = 0;
    int e;
    for (size_t i = 0; i < sizeof(builtins) / sizeof(*builtins); ++i) {
      struct lgru_builtin *builtin = &builtins[i];
      if (strcmp(argv[1], builtin->name) == 0) {
        is_builtin = 1;
        e = luaL_loadbuffer(L, builtin->script, strlen(builtin->script),
                            builtin->name);
        break;
      }
    }
    if (!is_builtin)
      e = luaL_loadfile(L, argv[1]);
    if (e) {
      printf("failed to load script `%s`\n", argv[1]);
      return e;
    }
    for (int i = 2; i < argc; ++i)
      lua_pushstring(L, argv[i]);
    e = lua_pcall(L, argc - 2, LUA_MULTRET, 0);
    if (e)
      puts(lua_tostring(L, -1));
    else if (lua_gettop(L) > 0)
      e = lua_tointeger(L, 1);
    lua_close(L);
    return e;
  }
  else {
    puts("libgru-0.1\n"
         "build date: " __TIME__ ", " __DATE__ "\n"
         "written by: glank\n"
         "invocation: `gru <script> [args...]`\n"
         "the following builtin scripts are available:");
    for (size_t i = 0; i < sizeof(builtins) / sizeof(*builtins); ++i) {
      struct lgru_builtin *builtin = &builtins[i];
      printf("  `%s`\n", builtin->usage);
    }
    return 0;
  }
}
示例#13
0
void Script::LoadFile(const char * fileName)
{

	if(luaL_loadfile(state,fileName) != 0)
		std::cout << lua_tostring(state,-1);
}
示例#14
0
文件: main.cpp 项目: Snegohod/xupnpd
int main(int argc,char** argv)
{
    const char* p=strrchr(argv[0],'/');

    int rc;

    if(p)
    {
        char location[512];
        int n=p-argv[0];
        if(n>=sizeof(location))
            n=sizeof(location)-1;
        strncpy(location,argv[0],n);
        location[n]=0;

        rc=chdir(location);

        argv[0]=(char*)p+1;
    }

    const char* root=getenv("XUPNPDROOTDIR");
    if(root && *root)
        rc=chdir(root);

    {
        FILE* fp=fopen("xupnpd.lua","r");
        if(fp)
            fclose(fp);
        else
            rc=chdir("/usr/share/xupnpd/");
    }

    lua_State* L=lua_open();
    if(L)
    {
        luaL_openlibs(L);
        luaopen_luaxlib(L);
        luaopen_luaxcore(L);
        luaopen_luajson(L);

        lua_newtable(L);
        for(int i=0;i<argc;i++)
        {
            lua_pushinteger(L,i+1);
            lua_pushstring(L,argv[i]);
            lua_rawset(L,-3);        
        }
        lua_setglobal(L,"arg");

//        char initfile[128];
//        snprintf(initfile,sizeof(initfile),"%s.lua",argv[0]);
        const char initfile[]="xupnpd.lua";

        if(luaL_loadfile(L,initfile) || lua_pcall(L,0,0,0))
        {
            const char* s=lua_tostring(L,-1);

            if(core::detached)
                syslog(LOG_INFO,"%s",s);
            else
                fprintf(stderr,"%s\n",s);

            lua_pop(L,1);
        }

        lua_close(L);
    }                                    
    
    return 0;
}
示例#15
0
int ReportedDoFile(lua_State *L, const char* filename)
{
    luaL_loadfile(L, filename);
    return ReportedDoCall(L, 0, 0);
}
示例#16
0
bool cMeshBuilder::LoadAsset(const char* i_path)
{
	bool wereThereErrors = false;

	// Create a new Lua state
	lua_State* luaState = NULL;
	{
		luaState = luaL_newstate();
		if (!luaState)
		{
			wereThereErrors = true;
			std::cerr << "Failed to create a new Lua state\n";
			goto OnExit;
		}
	}

	// Load the asset file as a "chunk",
	// meaning there will be a callable function at the top of the stack
	{
		//i_path = "../../../Assets/cube.txt";
		const int luaResult = luaL_loadfile(luaState, i_path);
		if (luaResult != LUA_OK)
		{
			wereThereErrors = true;
			std::cerr << lua_tostring(luaState, -1);
			// Pop the error message
			lua_pop(luaState, 1);
			goto OnExit;
		}
		else
		{
			//std::cout << "Loaded Lua File \n";
		}
	}

	// Execute the "chunk", which should load the asset
	// into a table at the top of the stack
	{
		const int argumentCount = 0;
		const int returnValueCount = LUA_MULTRET;	// Return _everything_ that the file returns
		const int noMessageHandler = 0;
		const int luaResult = lua_pcall(luaState, argumentCount, returnValueCount, noMessageHandler);
		if (luaResult == LUA_OK)
		{
			// A well-behaved asset file will only return a single value
			const int returnedValueCount = lua_gettop(luaState);
			if (returnedValueCount == 1)
			{
				// A correct asset file _must_ return a table
				if (!lua_istable(luaState, -1))
				{
					wereThereErrors = true;
					std::cerr << "Asset files must return a table (instead of a " <<
						luaL_typename(luaState, -1) << ")\n";
					// Pop the returned non-table value
					lua_pop(luaState, 1);
					goto OnExit;
				}
			}
			else
			{
				wereThereErrors = true;
				std::cerr << "Asset files must return a single table (instead of " <<
					returnedValueCount << " values)\n";
				// Pop every value that was returned
				lua_pop(luaState, returnedValueCount);
				goto OnExit;
			}
		}
		else
		{
			wereThereErrors = true;
			std::cerr << lua_tostring(luaState, -1);
			// Pop the error message
			lua_pop(luaState, 1);
			goto OnExit;
		}
	}

	// If this code is reached the asset file was loaded successfully,
	// and its table is now at index -1
	if (!LoadTableValues(*luaState))
	{
		wereThereErrors = true;
	}

	// Pop the table
	lua_pop(luaState, 1);

OnExit:

	if (luaState)
	{
		// If I haven't made any mistakes
		// there shouldn't be anything on the stack,
		// regardless of any errors encountered while loading the file:
		//assert(lua_gettop(luaState) == 0);

		//lua_close(luaState);
		//luaState = NULL;
	}

	return !wereThereErrors;
}
示例#17
0
文件: cbsdlua.c 项目: rhooper/cbsd
void lua_loadscript (lua_State *L, const char *fname) {
	if ( luaL_loadfile(L, fname) || lua_pcall(L,0,0,0) )
		cbsdlua_error(L, "cannot load config. file: %s", lua_tostring(L, -1));
}
示例#18
0
文件: console.c 项目: LuaDist/oil
static int handle_argv (lua_State *L, int argc, char **argv, int *interactive) {
  if (argv[1] == NULL) {  /* no arguments? */
    *interactive = 0;
    if (lua_stdin_is_tty())
      dotty(L);
    else
      dofile(L, NULL);  /* executes stdin as a file */
  }
  else {  /* other arguments; loop over them */
    int i;
    for (i = 1; argv[i] != NULL; i++) {
      if (argv[i][0] != '-') break;  /* not an option? */
      switch (argv[i][1]) {  /* option */
        case '-': {  /* `--' */
          if (argv[i][2] != '\0') {
            print_usage();
            return 1;
          }
          i++;  /* skip this argument */
          goto endloop;  /* stop handling arguments */
        }
        case '\0': {
          clearinteractive(interactive);
          dofile(L, NULL);  /* executes stdin as a file */
          break;
        }
        case 'i': {
          *interactive = 2;  /* force interactive mode after arguments */
          break;
        }
        case 'v': {
          clearinteractive(interactive);
          print_version();
          break;
        }
        case 'e': {
          const char *chunk = argv[i] + 2;
          clearinteractive(interactive);
          if (*chunk == '\0') chunk = argv[++i];
          if (chunk == NULL) {
            print_usage();
            return 1;
          }
          if (dostring(L, chunk, "=(command line)") != 0)
            return 1;
          break;
        }
        case 'l': {
          const char *filename = argv[i] + 2;
          if (*filename == '\0') filename = argv[++i];
          if (filename == NULL) {
            print_usage();
            return 1;
          }
          if (dolibrary(L, filename))
            return 1;  /* stop if file fails */
          break;
        }
        default: {
          clearinteractive(interactive);
          print_usage();
          return 1;
        }
      }
    } endloop:
    if (argv[i] != NULL) {
      int status;
      const char *filename = argv[i];
      int narg = getargs(L, argc, argv, i);  /* collect arguments */
      lua_setglobal(L, "arg");
      clearinteractive(interactive);
      status = luaL_loadfile(L, filename);
      lua_insert(L, -(narg+1));
      if (status == 0)
        status = docall(L, narg, 0);
      else
        lua_pop(L, narg);      
      return report(L, status);
    }
  }
  return 0;
}
示例#19
0
bool GuiManager::isValidShipFile(const char *srcFilename,
                                 BerryBotsEngine *engine) {
  // TODO: Is this too slow? Should we keep this list in the cache so we don't
  //       have to do this on every startup / refresh - at least for packaged
  //       ships? In fact, just the presence in the cache could be considered
  //       a sign of validity.
  // TODO: Move this out of the GUI code.
  if (fileManager_->isLuaFilename(srcFilename)
      || fileManager_->isZipFilename(srcFilename)) {
    char *shipDir = 0;
    char *shipFilename = 0;
    try {
      fileManager_->loadShipFileData(getShipsDir().c_str(), srcFilename,
                                     &shipDir, &shipFilename,
                                     getCacheDir().c_str());
    } catch (FileNotFoundException *fnfe) {
      // Only possible if user deletes file from disk after we find it on disk
      // but before we validate it. Seems safe to fail silently.
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      delete fnfe;
      return false;
    } catch (ZipperException *ze) {
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      errorConsole_->print(srcFilename);
      errorConsole_->print(": ");
      errorConsole_->println(ze->what());
      wxMessageDialog errorMessage(NULL, ze->what(), "Unzip failure",
                                   wxOK | wxICON_EXCLAMATION);
      errorMessage.ShowModal();
      delete ze;
      return false;
    } catch (PackagedSymlinkException *pse) {
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      errorConsole_->print(srcFilename);
      errorConsole_->print(": ");
      errorConsole_->println(pse->what());
      delete pse;
      return false;
    }
    lua_State *shipState;
    initShipState(&shipState, shipDir);

    if (luaL_loadfile(shipState, shipFilename)
        || engine->callUserLuaCode(shipState, 0, "", PCALL_VALIDATE)) {
      logErrorMessage(shipState, "Problem loading ship: %s");
      lua_close(shipState);
      delete shipDir;
      delete shipFilename;
      return false;
    }

    lua_getglobal(shipState, "configure");
    lua_getglobal(shipState, "init");
    if (lua_isnil(shipState, -1) || !lua_isnil(shipState, -2)) {
      lua_close(shipState);
      delete shipDir;
      delete shipFilename;
      return false;
    }
    
    lua_close(shipState);
    delete shipDir;
    delete shipFilename;
    return true;
  }
  return false;
}
示例#20
0
// Load an arbitrary lua file
void lua_dofile(lua_State *L, const char* path) {
    lua_pushcfunction(L, &traceback);
    luaL_loadfile(L, path) || lua_pcall(L, 0, LUA_MULTRET, -2);
}
示例#21
0
void CLuaFile::Init(const char *pFile)
{
    //close first
    Close();

    str_copy(m_aFilename, pFile, sizeof(m_aFilename));

    m_pLua = luaL_newstate();
	dbg_msg("lua", "%i kiB (loaded state)", lua_gc(m_pLua, LUA_GCCOUNT, 0));
    luaL_openlibs(m_pLua);
	dbg_msg("lua", "%i kiB (loaded libs)", lua_gc(m_pLua, LUA_GCCOUNT, 0));

    lua_atpanic(m_pLua, &Panic);

    //include
    lua_register(m_pLua, ToLower("Include"), this->Include);
    luaL_dostring(m_pLua, "package.path = \"./lua/?.lua;./lua/lib/?.lua\"\n");

    //config
    lua_register(m_pLua, ToLower("SetScriptUseSettingPage"), this->SetScriptUseSettingPage);
    lua_register(m_pLua, ToLower("SetScriptTitle"), this->SetScriptTitle);
    lua_register(m_pLua, ToLower("SetScriptInfo"), this->SetScriptInfo);

    //events
    lua_register(m_pLua, ToLower("AddEventListener"), this->AddEventListener);
    lua_register(m_pLua, ToLower("RemoveEventListener"), this->RemoveEventListener);

    //player
    lua_register(m_pLua, ToLower("GetPlayerIP"), this->GetPlayerIP);
    lua_register(m_pLua, ToLower("GetPlayerSpectateID"), this->GetPlayerSpectateID);
    lua_register(m_pLua, ToLower("GetPlayerName"), this->GetPlayerName);
    lua_register(m_pLua, ToLower("GetPlayerClan"), this->GetPlayerClan);
    lua_register(m_pLua, ToLower("GetPlayerCountry"), this->GetPlayerCountry);
    lua_register(m_pLua, ToLower("GetPlayerScore"), this->GetPlayerScore);
    lua_register(m_pLua, ToLower("GetPlayerPing"), this->GetPlayerPing);
    lua_register(m_pLua, ToLower("GetPlayerTeam"), this->GetPlayerTeam);
    lua_register(m_pLua, ToLower("GetPlayerSkin"), this->GetPlayerSkin);
    lua_register(m_pLua, ToLower("GetPlayerColorFeet"), this->GetPlayerColorFeet);
    lua_register(m_pLua, ToLower("GetPlayerColorBody"), this->GetPlayerColorBody);
    lua_register(m_pLua, ToLower("SetPlayerScore"), this->SetPlayerScore);
    lua_register(m_pLua, ToLower("SetPlayerName"), this->SetPlayerName);
    lua_register(m_pLua, ToLower("SetPlayerTeam"), this->SetPlayerTeam);
    lua_register(m_pLua, ToLower("SetPlayerClan"), this->SetPlayerClan);
    lua_register(m_pLua, ToLower("SetPlayerCountry"), this->SetPlayerCountry);
    lua_register(m_pLua, ToLower("SetPlayerSpectateID"), this->SetPlayerSpectateID);

    lua_register(m_pLua, ToLower("SetPlayerColorBody"), this->SetPlayerColorBody);
    lua_register(m_pLua, ToLower("SetPlayerColorFeet"), this->SetPlayerColorFeet);

    //character
    lua_register(m_pLua, ToLower("Emote"), this->Emote);
    lua_register(m_pLua, ToLower("GetCharacterPos"), this->GetCharacterPos);
    lua_register(m_pLua, ToLower("GetCharacterVel"), this->GetCharacterVel);
    lua_register(m_pLua, ToLower("SetCharacterPos"), this->SetCharacterPos);
    lua_register(m_pLua, ToLower("SetCharacterVel"), this->SetCharacterVel);

    //config
    lua_register(m_pLua, ToLower("GetConfigValue"), this->GetConfigValue);
    lua_register(m_pLua, ToLower("SetConfigValue"), this->SetConfigValue);

    //console
    lua_register(m_pLua, ToLower("Print"), this->Print);
    lua_register(m_pLua, ToLower("Console"), this->Console);

    //game
    lua_register(m_pLua, ToLower("GetGameType"), this->GetGameType);
    lua_register(m_pLua, ToLower("IsTeamplay"), this->IsTeamplay);

    //message
    //  lua_register(m_pLua, ToLower("GetNetError"), this->GetNetError);
    lua_register(m_pLua, ToLower("SendPacket"), this->SendPacket);
    lua_register(m_pLua, ToLower("AddModFile"), this->AddModFile);
    lua_register(m_pLua, ToLower("DeleteModFile"), this->DeleteModFile);
    lua_register(m_pLua, ToLower("SendFile"), this->SendFile);


    //collision
    lua_register(m_pLua, ToLower("IntersectLine"), this->IntersectLine);
    lua_register(m_pLua, ToLower("GetTile"), this->GetTile);
    lua_register(m_pLua, ToLower("SetTile"), this->SetTile);
    lua_register(m_pLua, ToLower("GetMapWidth"), this->GetMapWidth);
    lua_register(m_pLua, ToLower("GetMapHeight"), this->GetMapHeight);

    //Chat
    lua_register(m_pLua, ToLower("SendBroadcast"), this->SendBroadcast);
    lua_register(m_pLua, ToLower("SendChat"), this->SendChat);
    lua_register(m_pLua, ToLower("SendChatTarget"), this->SendChatTarget);

    //Entities
    lua_register(m_pLua, ToLower("EntityFind"), this->EntityFind);
    lua_register(m_pLua, ToLower("EntityGetCharacterId"), this->EntityGetCharacterId);
    lua_register(m_pLua, ToLower("EntityGetPos"), this->EntityGetPos);
    lua_register(m_pLua, ToLower("EntitySetPos"), this->EntitySetPos);
    lua_register(m_pLua, ToLower("EntityDestroy"), this->EntityDestroy);
    lua_register(m_pLua, ToLower("ProjectileFind"), this->ProjectileFind);
    lua_register(m_pLua, ToLower("ProjectileGetWeapon"), this->ProjectileGetWeapon);
    lua_register(m_pLua, ToLower("ProjectileGetOwner"), this->ProjectileGetOwner);
    lua_register(m_pLua, ToLower("ProjectileGetPos"), this->ProjectileGetPos);
    lua_register(m_pLua, ToLower("ProjectileGetDir"), this->ProjectileGetDir);
    lua_register(m_pLua, ToLower("ProjectileGetLifespan"), this->ProjectileGetLifespan);
    lua_register(m_pLua, ToLower("ProjectileGetExplosive"), this->ProjectileGetExplosive);
    lua_register(m_pLua, ToLower("ProjectileGetSoundImpact"), this->ProjectileGetSoundImpact);
    lua_register(m_pLua, ToLower("ProjectileGetStartTick"), this->ProjectileGetStartTick);
    lua_register(m_pLua, ToLower("ProjectileSetWeapon"), this->ProjectileSetWeapon);
    lua_register(m_pLua, ToLower("ProjectileSetOwner"), this->ProjectileSetOwner);
    lua_register(m_pLua, ToLower("ProjectileSetStartPos"), this->ProjectileSetStartPos);
    lua_register(m_pLua, ToLower("ProjectileSetDir"), this->ProjectileSetDir);
    lua_register(m_pLua, ToLower("ProjectileSetLifespan"), this->ProjectileSetLifespan);
    lua_register(m_pLua, ToLower("ProjectileSetExplosive"), this->ProjectileSetExplosive);
    lua_register(m_pLua, ToLower("ProjectileSetSoundImpact"), this->ProjectileSetSoundImpact);
    lua_register(m_pLua, ToLower("ProjectileSetStartTick"), this->ProjectileSetStartTick);
    lua_register(m_pLua, ToLower("ProjectileCreate"), this->ProjectileCreate);
    lua_register(m_pLua, ToLower("LaserCreate"), this->LaserCreate);


    //game
    lua_register(m_pLua, ToLower("CreateExplosion"), this->CreateExplosion);
    lua_register(m_pLua, ToLower("CreateDeath"), this->CreateDeath);
    lua_register(m_pLua, ToLower("CreateDamageIndicator"), this->CreateDamageIndicator);
    lua_register(m_pLua, ToLower("CreateHammerHit"), this->CreateHammerHit);
    lua_register(m_pLua, ToLower("CreateSound"), this->CreateSound);

    //tunings
    lua_register(m_pLua, ToLower("GetTuning"), this->GetTuning);
    lua_register(m_pLua, ToLower("SetTuning"), this->SetTuning);

    lua_register(m_pLua, ToLower("CharacterSetInputDirection"), this->CharacterSetInputDirection);
    lua_register(m_pLua, ToLower("CharacterSetInputJump"), this->CharacterSetInputJump);
    lua_register(m_pLua, ToLower("CharacterSetInputWeapon"), this->CharacterSetInputWeapon);
    lua_register(m_pLua, ToLower("CharacterSetInputTarget"), this->CharacterSetInputTarget);
    lua_register(m_pLua, ToLower("CharacterSetInputHook"), this->CharacterSetInputHook);
    lua_register(m_pLua, ToLower("CharacterSetInputFire"), this->CharacterSetInputFire);
    lua_register(m_pLua, ToLower("CharacterGetCoreJumped"), this->CharacterGetCoreJumped);
    lua_register(m_pLua, ToLower("CharacterSpawn"), this->CharacterSpawn);
    lua_register(m_pLua, ToLower("CharacterIsAlive"), this->CharacterIsAlive);
    lua_register(m_pLua, ToLower("CharacterKill"), this->CharacterKill);
    lua_register(m_pLua, ToLower("CharacterIsGrounded"), this->CharacterIsGrounded);
    lua_register(m_pLua, ToLower("CharacterIncreaseHealth"), this->CharacterIncreaseHealth);
    lua_register(m_pLua, ToLower("CharacterIncreaseArmor"), this->CharacterIncreaseArmor);
    lua_register(m_pLua, ToLower("CharacterSetAmmo"), this->CharacterSetAmmo);
    lua_register(m_pLua, ToLower("CharacterGetAmmo"), this->CharacterGetAmmo);
    lua_register(m_pLua, ToLower("CharacterGetInputTarget"), this->CharacterGetInputTarget);
    lua_register(m_pLua, ToLower("CharacterGetActiveWeapon"), this->CharacterGetActiveWeapon);
    lua_register(m_pLua, ToLower("CharacterSetActiveWeapon"), this->CharacterSetActiveWeapon);
    lua_register(m_pLua, ToLower("CharacterDirectInput"), this->CharacterDirectInput);
    lua_register(m_pLua, ToLower("CharacterPredictedInput"), this->CharacterPredictedInput);
    lua_register(m_pLua, ToLower("CharacterGetHealth"), this->CharacterGetHealth);
    lua_register(m_pLua, ToLower("CharacterGetArmor"), this->CharacterGetArmor);
    lua_register(m_pLua, ToLower("CharacterSetHealth"), this->CharacterSetHealth);
    lua_register(m_pLua, ToLower("CharacterSetArmor"), this->CharacterSetArmor);
    lua_register(m_pLua, ToLower("CharacterTakeDamage"), this->CharacterTakeDamage);

    lua_register(m_pLua, ToLower("SendCharacterInfo"), this->SendCharacterInfo);

    lua_register(m_pLua, ToLower("SetAutoRespawn"), this->SetAutoRespawn);

    lua_register(m_pLua, ToLower("Win"), this->Win);
    lua_register(m_pLua, ToLower("SetGametype"), this->SetGametype);

    lua_register(m_pLua, ToLower("DummyCreate"), this->DummyCreate);
    lua_register(m_pLua, ToLower("IsDummy"), this->IsDummy);

    //version
    lua_register(m_pLua, ToLower("CheckVersion"), this->CheckVersion);
    lua_register(m_pLua, ToLower("GetVersion"), this->GetVersion);

    lua_register(m_pLua, ToLower("CreateDirectory"), this->CreateDirectory);
    lua_register(m_pLua, ToLower("GetDate"), this->GetDate);

    lua_register(m_pLua, ToLower("GetTick"), this->GetTick);
    lua_register(m_pLua, ToLower("GetTickSpeed"), this->GetTickSpeed);

    //MySQL - Yeah
    lua_register(m_pLua, ToLower("MySQLConnect"), this->MySQLConnect);
    lua_register(m_pLua, ToLower("MySQLEscapeString"), this->MySQLEscapeString);
    lua_register(m_pLua, ToLower("MySQLSelectDatabase"), this->MySQLSelectDatabase);
    lua_register(m_pLua, ToLower("MySQLIsConnected"), this->MySQLIsConnected);
    lua_register(m_pLua, ToLower("MySQLQuery"), this->MySQLQuery);
    lua_register(m_pLua, ToLower("MySQLClose"), this->MySQLClose);
    lua_register(m_pLua, ToLower("MySQLFetchResults"), this->MySQLFetchResults);

    m_pLuaShared = new CLuaShared<CLuaFile>(this);

    lua_pushlightuserdata(m_pLua, this);
    lua_setglobal(m_pLua, "pLUA");

    lua_register(m_pLua, ToLower("errorfunc"), this->ErrorFunc);

	dbg_msg("lua", "%i kiB (loaded fx)", lua_gc(m_pLua, LUA_GCCOUNT, 0));
    if (luaL_loadfile(m_pLua, m_aFilename) == 0)
    {
        lua_pcall(m_pLua, 0, LUA_MULTRET, 0);
        ErrorFunc(m_pLua);
		dbg_msg("lua", "%i kiB (loaded file)", lua_gc(m_pLua, LUA_GCCOUNT, 0));
    }
    else
    {
        ErrorFunc(m_pLua);
        dbg_msg("lua", "fail to load file: %s", pFile);
        Close();
        return;
    }
}
示例#22
0
bool loadDictionaryFromFile(
    const std::string& filename,
    ghoul::Dictionary& dictionary,
    lua_State* state
    )
{
    const static std::string _loggerCat = "lua_loadDictionaryFromFile";

    if (state == nullptr) {
        if (_state == nullptr) {
            LDEBUG("Creating Lua state");
            _state = luaL_newstate();
            if (_state == nullptr) {
                LFATAL("Error creating new Lua state: Memory allocation error");
                return false;
            }
            LDEBUG("Open libraries");
            luaL_openlibs(_state);
        }
        state = _state;
    }

    if (filename.empty()) {
        LERROR("Filename was empty");
        return false;
    }

    if (!FileSys.fileExists(absPath(filename))) {
        LERROR("File '" << absPath(filename) << "' did not exist");
        return false;
    }

    LDEBUG("Loading dictionary script '" << filename << "'");
    int status = luaL_loadfile(state, absPath(filename).c_str());
    if (status != LUA_OK) {
        LERROR("Error loading script: '" << lua_tostring(state, -1) << "'");
        return false;
    }

    LDEBUG("Executing script");
    if (lua_pcall(state, 0, LUA_MULTRET, 0)) {
        LERROR("Error executing script: " << lua_tostring(state, -1));
        return false;
    }

    if (lua_isnil(state, -1)) {
        LERROR("Error in script: '" << filename << "'. Script did not return anything.");
        return false;
    }

    if (!lua_istable(state, -1)) {
        LERROR("Error in script: '" << filename << "'. Script did not return a table.");
        return false;
    }

    luaDictionaryFromState(state, dictionary);

    // Clean up after ourselves by cleaning the stack
    lua_settop(state, 0);

    return true;
}
示例#23
0
int icelua_init(void)
{
	int i, argct;
	
	// create states
	lstate_client = (boot_mode & 1 ? luaL_newstate() : NULL);
	lstate_server = (boot_mode & 2 ? luaL_newstate() : NULL);
	
	// create tables
	if(lstate_client != NULL)
	{
		lua_newtable(lstate_client);
		lua_setglobal(lstate_client, "client");
		lua_newtable(lstate_client);
		lua_setglobal(lstate_client, "common");
		lua_pushvalue(lstate_client, LUA_GLOBALSINDEX);
		lua_setglobal(lstate_client, "_G");
	}
	
	if(lstate_server != NULL)
	{
		lua_newtable(lstate_server);
		lua_setglobal(lstate_server, "server");
		lua_newtable(lstate_server);
		lua_setglobal(lstate_server, "common");
		lua_pushvalue(lstate_server, LUA_GLOBALSINDEX);
		lua_setglobal(lstate_server, "_G");
	}
	
	// load stuff into them
#ifndef DEDI
	icelua_loadfuncs(lstate_client, "client", icelua_client);
	icelua_loadfuncs(lstate_client, "client", icelua_common);
	icelua_loadfuncs(lstate_client, "common", icelua_common);
	icelua_loadfuncs(lstate_client, "client", icelua_common_client);
	icelua_loadfuncs(lstate_client, "common", icelua_common_client);
#endif
	icelua_loadfuncs(lstate_server, "server", icelua_server);
	icelua_loadfuncs(lstate_server, "server", icelua_common);
	icelua_loadfuncs(lstate_server, "common", icelua_common);
	icelua_loadfuncs(lstate_server, "server", icelua_common_server);
	icelua_loadfuncs(lstate_server, "common", icelua_common_server);
	
	// load some lua base libraries
	icelua_loadbasefuncs(lstate_client);
	icelua_loadbasefuncs(lstate_server);
	
	// shove some pathnames / versions in
	if(lstate_server != NULL)
	{
		lua_getglobal(lstate_server, "common");
		lua_getglobal(lstate_server, "server");
		lua_pushstring(lstate_server, mod_basedir+4);
		lua_setfield(lstate_server, -2, "base_dir");
		lua_pop(lstate_server, 1);
		lua_pushstring(lstate_server, mod_basedir+4);
		lua_setfield(lstate_server, -2, "base_dir");
		lua_pop(lstate_server, 1);
		
		icelua_pushversion(lstate_server, "common");
		icelua_pushversion(lstate_server, "server");
	}
	
	if(lstate_client != NULL)
	{
		icelua_pushversion(lstate_client, "common");
		icelua_pushversion(lstate_client, "client");
	}
	
	/*
	NOTE:
	to call stuff, use lua_pcall.
	DO NOT use lua_call! if it fails, it will TERMINATE the program!
	*/
	
	// quick test
	// TODO: set up a "convert/filter file path" function
	// TODO: split the client/server inits
	char xpath[128];
	snprintf(xpath, 128, "%s/main_server.lua", mod_basedir);
	
	if((lstate_server != NULL) && luaL_loadfile(lstate_server, xpath) != 0)
	{
		printf("ERROR loading server Lua: %s\n", lua_tostring(lstate_server, -1));
		return 1;
	}
	
	argct = (main_largstart == -1 || (main_largstart >= main_argc)
		? 0
		: main_argc - main_largstart);
	
	if(lstate_server != NULL)
	{
		for(i = 0; i < argct; i++)
			lua_pushstring(lstate_server, main_argv[i+main_largstart]);
		if(lua_pcall(lstate_server, argct, 0, 0) != 0)
		{
			printf("ERROR running server Lua: %s\n", lua_tostring(lstate_server, -1));
			lua_pop(lstate_server, 1);
			return 1;
		}
	}
	
	if(lstate_client != NULL && mod_basedir != NULL)
		if(icelua_initfetch())
			return 1;
	
	// dispatch initial connect
	if(lstate_server != NULL && lstate_client != NULL)
	{
		lua_getglobal(lstate_server, "server");
		lua_getfield(lstate_server, -1, "hook_connect");
		lua_remove(lstate_server, -2);
		if(!lua_isnil(lstate_server, -1))
		{
			lua_pushboolean(lstate_server, 1);
			lua_newtable(lstate_server);
			
			lua_pushstring(lstate_server, "local");
			lua_setfield(lstate_server, -2, "proto");
			lua_pushnil(lstate_server);
			lua_setfield(lstate_server, -2, "addr");
			
			if(lua_pcall(lstate_server, 2, 0, 0) != 0)
			{
				printf("ERROR running server Lua (hook_connect): %s\n", lua_tostring(lstate_server, -1));
				lua_pop(lstate_server, 2);
				return 1;
			}
		} else {
			lua_pop(lstate_server, 1);
		}
	}
	
	return 0;
}
示例#24
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;
}
示例#25
0
文件: main.c 项目: buaazp/zimg
/**
 * @brief sighandler the signal handler of zimg
 *
 * @param signal the signal zimg get
 * @param siginfo signal info
 * @param arg the arg for handler
 */
static void sighandler(int signal, siginfo_t *siginfo, void *arg) {
    char msg[128];
    msg[0] = '\0';
    str_lcat(msg, "----/--/-- --:--:--:------ [INFO] signal Terminal received zimg shutting down", sizeof(msg));
    //str_lcat(msg, strsignal(signal));
    log_handler(msg);
    write(STDOUT_FILENO, "\nbye bye!\n", 10);

    //evbase_t *evbase = (evbase_t *)arg;
    struct timeval tv = { .tv_usec = 100000, .tv_sec = 0 }; /* 100 ms */
    event_base_loopexit(evbase, &tv);
}

/**
 * @brief init_thread the init function of threads
 *
 * @param htp evhtp object
 * @param thread the current thread
 * @param arg the arg for init
 */
void init_thread(evhtp_t *htp, evthr_t *thread, void *arg) {
    thr_arg_t *thr_args;
    thr_args = calloc(1, sizeof(thr_arg_t));
    LOG_PRINT(LOG_DEBUG, "thr_args alloc");
    thr_args->thread = thread;

    char mserver[32];

    if (settings.cache_on == true) {
        memcached_st *memc = memcached_create(NULL);
        snprintf(mserver, 32, "%s:%d", settings.cache_ip, settings.cache_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        memcached_server_push(memc, servers);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NOREPLY, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        thr_args->cache_conn = memc;
        LOG_PRINT(LOG_DEBUG, "Memcached Connection Init Finished.");
        memcached_server_list_free(servers);
    } else
        thr_args->cache_conn = NULL;

    if (settings.mode == 2) {
        thr_args->ssdb_conn = NULL;
        memcached_st *beans = memcached_create(NULL);
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        thr_args->beansdb_conn = beans;
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        memcached_server_list_free(servers);
    } else if (settings.mode == 3) {
        thr_args->beansdb_conn = NULL;
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if (c->err) {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
        } else {
            thr_args->ssdb_conn = c;
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    thr_args->L = luaL_newstate();
    LOG_PRINT(LOG_DEBUG, "luaL_newstate alloc");
    if (thr_args->L != NULL) {
        luaL_openlibs(thr_args->L);
        luaL_openlib(thr_args->L, "zimg", zimg_lib, 0);
        luaL_openlib(thr_args->L, "log", loglib, 0);
    }
    luaL_loadfile(thr_args->L, settings.script_name);
    lua_pcall(thr_args->L, 0, 0, 0);

    evthr_set_aux(thread, thr_args);

    lua_State *L = luaL_newstate();
    if (L != NULL) {
        luaL_openlibs(L);
        if (luaL_loadfile(L, conf_file) || lua_pcall(L, 0, 0, 0)) {
            lua_close(L);
        } else {
            pthread_setspecific(gLuaStateKey, (void *)L);
        }
    }
}
示例#26
0
文件: lbaselib.c 项目: gitrider/wxsj2
static int luaB_loadfile (lua_State *L) {
  const char *fname = luaL_optstring(L, 1, NULL);
  return load_aux(L, luaL_loadfile(L, fname));
}
示例#27
0
文件: Config.cpp 项目: fU9ANg/ab
/**
* @brief 
*
* @param file
*/
void Config::readconfig (string file)
{
    lua_State* lua = luaL_newstate ();

    //加载脚本
    //int ret = luaL_loadfile (lua, "config.lua");
    int ret = luaL_loadfile (lua, file.c_str ());
    if (ret != 0)
    {
        lua_close (lua);
        return;
    }   
    //初始化
    ret = lua_pcall (lua, 0, 0, 0);
    if (ret != 0)
    {
        lua_close (lua);
        return;
    }
    //数据库地址
    lua_getglobal (lua,"db_host");
    db_host = lua_tostring (lua, -1);

    //数据库用户名
    lua_getglobal (lua,"db_username");
    db_username = lua_tostring (lua, -1);

    //数据库密码
    lua_getglobal (lua,"db_password");
    db_password = lua_tostring (lua, -1);

    //数据库名
    lua_getglobal (lua,"db_database");
    db_database = lua_tostring (lua, -1);

    //IP
    lua_getglobal (lua,"server_ip");
    server_ip = lua_tostring (lua, -1);

    //username
    lua_getglobal (lua, "username");
    username = lua_tostring(lua, -1);

    //passwd
    lua_getglobal (lua, "password");
    passwd = lua_tostring(lua, -1);

    // download_upload_server_ip
    lua_getglobal (lua, "download_upload_server_ip");
    download_upload_server_ip = lua_tostring(lua, -1);

    //端口
    lua_getglobal (lua,"server_port");
    server_port = lua_tointeger (lua, -1);

    // download_upload_server_port
    lua_getglobal (lua,"download_upload_server_port");
    download_upload_server_port = lua_tointeger (lua, -1);

    //学校id
    lua_getglobal (lua,"school_id");
    school_id = lua_tointeger (lua, -1);

    //游戏数量
    lua_getglobal (lua,"game_count");
    game_count = lua_tointeger (lua, -1);

    lua_pop (lua,8);

    lua_close (lua);
    return;
}
示例#28
0
文件: main_lua.c 项目: eswartz/emul
int tcf_lua(void) {
#else
int main(int argc, char ** argv) {
#endif
    int c;
    int ind;
    int error;
    const char * log_name = "-";
    const char * script_name = NULL;
    char * engine_name;
    lua_State *L;

    log_mode = 0;

#ifndef WIN32
    signal(SIGPIPE, SIG_IGN);
#endif
    ini_mdep();
    ini_trace();
    ini_events_queue();
    ini_asyncreq();

#if defined(_WRS_KERNEL)

    progname = "tcf";
    open_log_file("-");

#else

    progname = argv[0];

    /* Parse arguments */
    for (ind = 1; ind < argc; ind++) {
        const char * s = argv[ind];
        if (*s != '-') {
            break;
        }
        s++;
        while ((c = *s++) != '\0') {
            switch (c) {
            case 'l':
            case 'L':
            case 'S':
                if (*s == '\0') {
                    if (++ind >= argc) {
                        fprintf(stderr, "%s: error: no argument given to option '%c'\n", progname, c);
                        exit(1);
                    }
                    s = argv[ind];
                }
                switch (c) {
                case 'l':
                    log_mode = strtol(s, 0, 0);
                    break;

                case 'L':
                    log_name = s;
                    break;

                case 'S':
                    script_name = s;
                    break;

                default:
                    fprintf(stderr, "%s: error: illegal option '%c'\n", progname, c);
                    exit(1);
                }
                s = "";
                break;

            default:
                fprintf(stderr, "%s: error: illegal option '%c'\n", progname, c);
                exit(1);
            }
        }
    }
    if (ind >= argc) {
        fprintf(stderr, "%s: error: no Lua script specified\n", progname);
        exit(1);
    }
    engine_name = argv[ind++];
    if (ind < argc) {
        fprintf(stderr, "%s: error: too many arguments\n", progname);
        exit(1);
    }

    open_log_file(log_name);

#endif

    if (script_name != NULL) {
        if((lua_read_command_state.req.u.fio.fd = open(script_name, O_RDONLY, 0)) < 0) {
            fprintf(stderr, "%s: error: cannot open script: %s\n", progname, script_name);
            exit(1);
        }
    } else {
        lua_read_command_state.req.u.fio.fd = fileno(stdin);
    }

    discovery_start();

    if((luastate = L = luaL_newstate()) == NULL) {
        fprintf(stderr, "error from luaL_newstate\n");
        exit(1);
    }
    luaL_openlibs(L);

    luaL_register(L, "tcf", tcffuncs);
    lua_pop(L, 1);

    /* Peer metatable */
    luaL_newmetatable(L, "tcf_peer");
    luaL_register(L, NULL, peerfuncs);
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__index");     /* m.__index = m */
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */
    lua_pop(L, 1);

    /* Protocol metatable */
    luaL_newmetatable(L, "tcf_protocol");
    luaL_register(L, NULL, protocolfuncs);
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__index");     /* m.__index = m */
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */
    lua_pop(L, 1);

    /* Channel metatable */
    luaL_newmetatable(L, "tcf_channel");
    luaL_register(L, NULL, channelfuncs);
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__index");     /* m.__index = m */
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */
    lua_pop(L, 1);

    /* Post event metatable */
    luaL_newmetatable(L, "tcf_post_event");
    luaL_register(L, NULL, posteventfuncs);
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__index");     /* m.__index = m */
    lua_pushvalue(L, -1);
    lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */
    lua_pop(L, 1);

    lua_newtable(L);                    /* peers = {} */
    lua_newtable(L);                    /* m = {} */
    lua_pushstring(L, "v");             /* Values are weak */
    lua_setfield(L, -2, "__mode");      /* m.__mode = "v" */
    lua_setmetatable(L, -2);            /* setmetatable(peer, m) */
    peers_refp = luaref_new(L, NULL);
    peer_server_add_listener(peer_server_changes, L);

    if((error = luaL_loadfile(L, engine_name)) != 0) {
        fprintf(stderr, "%s\n", lua_tostring(L,1));
        exit(1);
    }

    if((error = lua_pcall(L, 0, LUA_MULTRET, 0)) != 0) {
        fprintf(stderr, "%s\n", lua_tostring(L,1));
        exit(1);
    }

    /* Process events - must run on the initial thread since ptrace()
     * returns ECHILD otherwise, thinking we are not the owner. */
    run_event_loop();

    lua_close(L);
    return 0;
}
示例#29
0
static int dofile(lua_State *L, const char *name)
{
    int status = luaL_loadfile(L, name) || docall(L, 0, 1);
    return report(L, status);
}
示例#30
0
static int lua_parse_and_execute(lua_State * L, char *input_code)
{
	int error = 0;

	if (zstr(input_code)) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No code to execute!\n");
		return 1;
	}

	while(input_code && (*input_code == ' ' || *input_code == '\n' || *input_code == '\r')) input_code++;
	
	if (*input_code == '~') {
		char *buff = input_code + 1;
		error = luaL_loadbuffer(L, buff, strlen(buff), "line") || docall(L, 0, 0, 0);	//lua_pcall(L, 0, 0, 0);
	} else if (!strncasecmp(input_code, "#!/lua", 6)) {
		char *buff = input_code + 6;
		error = luaL_loadbuffer(L, buff, strlen(buff), "line") || docall(L, 0, 0, 0);	//lua_pcall(L, 0, 0, 0);
	} else {
		char *args = strchr(input_code, ' ');
		if (args) {
			char *code = NULL;
			int x, argc;
			char *argv[128] = { 0 };
			*args++ = '\0';

			if ((argc = switch_separate_string(args, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
				switch_stream_handle_t stream = { 0 };
				SWITCH_STANDARD_STREAM(stream);

				stream.write_function(&stream, " argv = {[0]='%y', ", input_code);
				for (x = 0; x < argc; x++) {
					stream.write_function(&stream, "'%y'%s", argv[x], x == argc - 1 ? "" : ", ");
				}
				stream.write_function(&stream, " };");
				code = (char *) stream.data;
			} else {
				code = switch_mprintf("argv = {[0]='%s'};", input_code);
			}

			if (code) {
				error = luaL_loadbuffer(L, code, strlen(code), "line") || docall(L, 0, 0, 0);
				switch_safe_free(code);
			}
		} else {
			// Force empty argv table
			char *code = NULL;
			code = switch_mprintf("argv = {[0]='%s'};", input_code);
			error = luaL_loadbuffer(L, code, strlen(code), "line") || docall(L, 0, 0, 0);
			switch_safe_free(code);
		}

		if (!error) {
			char *file = input_code, *fdup = NULL;

			if (!switch_is_file_path(file)) {
				fdup = switch_mprintf("%s/%s", SWITCH_GLOBAL_dirs.script_dir, file);
				switch_assert(fdup);
				file = fdup;
			}
			error = luaL_loadfile(L, file) || docall(L, 0, 0, 0);
			switch_safe_free(fdup);
		}
	}

	if (error) {
		const char *err = lua_tostring(L, -1);
		if (!zstr(err)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s\n", err);
		}
		lua_pop(L, 1);			/* pop error message from the stack */
	}

	return error;
}