Exemplo n.º 1
0
bool luaW_toconfig(lua_State *L, int index, config &cfg)
{
	if (!lua_checkstack(L, LUA_MINSTACK))
		return false;

	// Get the absolute index of the table.
	index = lua_absindex(L, index);
	int initial_top = lua_gettop(L);

	switch (lua_type(L, index))
	{
		case LUA_TTABLE:
			break;
		case LUA_TUSERDATA:
		{
			if (vconfig * ptr = static_cast<vconfig *> (luaL_testudata(L, index, vconfigKey))) {
				cfg = ptr->get_parsed_config();
				return true;
			} else {
				return false;
			}
		}
		case LUA_TNONE:
		case LUA_TNIL:
			return true;
		default:
			return false;
	}

	// First convert the children (integer indices).
	for (int i = 1, i_end = lua_rawlen(L, index); i <= i_end; ++i)
	{
		lua_rawgeti(L, index, i);
		if (!lua_istable(L, -1)) return_misformed();
		lua_rawgeti(L, -1, 1);
		char const *m = lua_tostring(L, -1);
		if (!m) return_misformed();
		lua_rawgeti(L, -2, 2);
		if (!luaW_toconfig(L, -1, cfg.add_child(m)))
			return_misformed();
		lua_pop(L, 3);
	}

	// Then convert the attributes (string indices).
	for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1))
	{
		if (lua_isnumber(L, -2)) continue;
		if (!lua_isstring(L, -2)) return_misformed();
		config::attribute_value &v = cfg[lua_tostring(L, -2)];
		if (lua_istable(L, -1)) {
			int subindex = lua_absindex(L, -1);
			std::ostringstream str;
			for (int i = 1, i_end = lua_rawlen(L, subindex); i <= i_end; ++i, lua_pop(L, 1)) {
				lua_rawgeti(L, -1, i);
				config::attribute_value item;
				if (!luaW_toscalar(L, -1, item)) return_misformed();
				if (i > 1) str << ',';
				str << item;
			}
			// If there are any string keys, it's misformed
			for (lua_pushnil(L); lua_next(L, subindex); lua_pop(L, 1)) {
				if (!lua_isnumber(L, -2)) return_misformed();
			}
			v = str.str();
		} else if (!luaW_toscalar(L, -1, v)) return_misformed();
	}

	lua_settop(L, initial_top);
	return true;
}
Exemplo n.º 2
0
projectile_id projectile_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_projectile_data, lua_tostring(L, idx));
}
Exemplo n.º 3
0
tileset_id tileset_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_tileset_data, lua_tostring(L, idx));
}
Exemplo n.º 4
0
class_id class_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_class_data, lua_tostring(L, idx));
}
Exemplo n.º 5
0
spell_id spell_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_spell_data, lua_tostring(L, idx));
}
Exemplo n.º 6
0
static int 
concat_fname(lua_State *L, const char *fname)
{
  const char *from = lua_tostring(L, -1);

#ifdef _WIN32

  const char *s;
  SB sb;
  sbinit(&sb);
  sbaddn(&sb, from, strlen(from));
  if (fname==0)
    return sbpush(L, &sb);
  /* Handle absolute part of fname */
  if (fname[0]=='/' || fname[0]=='\\') {
    if (fname[1]=='/' || fname[1]=='\\') {
      sb.len = 0;                            /* Case //abcd */
      sbaddn(&sb, "//", 2);
    } else {
      char drive;
      if (sb.len >= 2 && sb.buffer[1]==':'   /* Case "/abcd" */
          && isalpha((unsigned char)(sb.buffer[0])) )
        drive = sb.buffer[0];
      else
        drive = _getdrive() + 'A' - 1;
      sb.len = 0;
      sbadd1(&sb, drive);
      sbaddn(&sb, ":/", 2);
    }
  } else if (fname[0] && 	              /* Case "x:abcd"   */
             isalpha((unsigned char)(fname[0])) && fname[1]==':') {
    if (fname[2]!='/' && fname[2]!='\\') {
      if (sb.len < 2 || sb.buffer[1]!=':' 
          || !isalpha((unsigned char)(sb.buffer[0]))
          || (toupper((unsigned char)sb.buffer[0]) !=
              toupper((unsigned char)fname[0]) ) ) 
        {
          int l;
          char drv[4];
          sb.len = 0;
          drv[0]=fname[0]; drv[1]=':'; drv[2]='.'; drv[3]=0;
          l = GetFullPathNameA(drv, sb.maxlen, sb.buffer, 0);
          if (l > sb.maxlen) {
            sbgrow(&sb, l+1);
            l = GetFullPathNameA(drv, sb.maxlen, sb.buffer, 0);
          }
          if (l <= 0)
            sbaddn(&sb, drv, 3);
          else
            sb.len += l;
        }
      fname += 2;
    } else {
      sb.len = 0;                              /* Case "x:/abcd"  */
      sbadd1(&sb, toupper((unsigned char)fname[0])); 
      sbaddn(&sb, ":/", 2);
      fname += 2;
      while (*fname == '/' || *fname == '\\')
        fname += 1;
    }
  }
  /* Process path components */
  for (;;)
  {
    while (*fname=='/' || *fname=='\\')
      fname ++;
    if (*fname == 0)
      return sbpush(L, &sb);
    if (fname[0]=='.') {
      if (fname[1]=='/' || fname[1]=='\\' || fname[1]==0) {
	fname += 1;
	continue;
      }
      if (fname[1]=='.')
        if (fname[2]=='/' || fname[2]=='\\' || fname[2]==0) {
          size_t l;
	  fname += 2;
          lua_pushcfunction(L, lua_dirname);
          sbpush(L, &sb);
          lua_call(L, 1, 1);
          s = lua_tolstring(L, -1, &l);
          sbinit(&sb);
          sbaddn(&sb, s, l);
          lua_pop(L, 1);
	  continue;
      }
    }
    if (sb.len==0 || 
        (sb.buffer[sb.len-1]!='/' && sb.buffer[sb.len-1]!='\\') )
      sbadd1(&sb, '/');
    while (*fname && *fname!='/' && *fname!='\\')
      sbadd1(&sb, *fname++);
  }
             
#else
  SB sb;
  sbinit(&sb);

  if (fname && fname[0]=='/') 
    sbadd1(&sb, '/');
  else
    sbaddn(&sb, from, strlen(from));
  for (;;) {
    while (fname && fname[0]=='/')
      fname++;
    if (!fname || !fname[0]) {
      sbadd1(&sb, '/');
      while (sb.len > 1 && sb.buffer[sb.len-1]=='/')
        sb.len --;
      return sbpush(L, &sb);
    }
    if (fname[0]=='.') {
      if (fname[1]=='/' || fname[1]==0) {
	fname +=1;
	continue;
      }
      if (fname[1]=='.')
	if (fname[2]=='/' || fname[2]==0) {
	  fname +=2;
          while (sb.len > 0 && sb.buffer[sb.len-1]=='/')
            sb.len --;
          while (sb.len > 0 && sb.buffer[sb.len-1]!='/')
            sb.len --;
	  continue;
	}
    }
    if (sb.len == 0 || sb.buffer[sb.len-1] != '/')
      sbadd1(&sb, '/');
    while (*fname!=0 && *fname!='/')
      sbadd1(&sb, *fname++);
  }
  
  
#endif

}
Exemplo n.º 7
0
static void loaderror (lua_State *L, const char *filename) {
  luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
                lua_tostring(L, 1), filename, lua_tostring(L, -1));
}
Exemplo n.º 8
0
static gboolean
rspamd_symbols_cache_check_symbol (struct rspamd_task *task,
		struct symbols_cache *cache,
		struct cache_item *item,
		struct cache_savepoint *checkpoint,
		gdouble *total_diff)
{
	guint pending_before, pending_after;
	double t1, t2;
	gdouble diff;
	struct rspamd_task **ptask;
	lua_State *L;
	gboolean check = TRUE;
	const gdouble slow_diff_limit = 1e5;

	if (item->type & (SYMBOL_TYPE_NORMAL|SYMBOL_TYPE_CALLBACK)) {

		g_assert (item->func != NULL);
		/* Check has been started */
		setbit (checkpoint->processed_bits, item->id * 2);

		if (RSPAMD_TASK_IS_EMPTY (task) && !(item->type & SYMBOL_TYPE_EMPTY)) {
			check = FALSE;
		}
		else if (item->condition_cb != -1) {
			/* We also executes condition callback to check if we need this symbol */
			L = task->cfg->lua_state;
			lua_rawgeti (L, LUA_REGISTRYINDEX, item->condition_cb);
			ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
			rspamd_lua_setclass (L, "rspamd{task}", -1);
			*ptask = task;

			if (lua_pcall (L, 1, 1, 0) != 0) {
				msg_info_task ("call to condition for %s failed: %s",
						item->symbol, lua_tostring (L, -1));
				lua_pop (L, 1);
			}
			else {
				check = lua_toboolean (L, -1);
				lua_pop (L, 1);
			}
		}

		if (check) {
			t1 = rspamd_get_ticks ();
			pending_before = rspamd_session_events_pending (task->s);
			/* Watch for events appeared */
			rspamd_session_watch_start (task->s, rspamd_symbols_cache_watcher_cb,
					item);

			msg_debug_task ("execute %s, %d", item->symbol, item->id);
			item->func (task, item->user_data);

			t2 = rspamd_get_ticks ();
			diff = (t2 - t1) * 1e6;

			if (total_diff) {
				*total_diff += diff;
			}

			if (diff > slow_diff_limit) {
				msg_info_task ("slow rule: %s: %d ms", item->symbol,
						(gint)(diff / 1000.));
			}

			rspamd_set_counter (item, diff);
			rspamd_session_watch_stop (task->s);
			pending_after = rspamd_session_events_pending (task->s);

			if (pending_before == pending_after) {
				/* No new events registered */
				setbit (checkpoint->processed_bits, item->id * 2 + 1);

				return TRUE;
			}

			return FALSE;
		}
		else {
			msg_debug_task ("skipping check of %s as its condition is false",
					item->symbol);
			setbit (checkpoint->processed_bits, item->id * 2 + 1);

			return TRUE;
		}
	}
	else {
		setbit (checkpoint->processed_bits, item->id * 2);
		setbit (checkpoint->processed_bits, item->id * 2 + 1);

		return TRUE;
	}
}
Exemplo n.º 9
0
EventData::operator std::string() const {
    this->push();
    std::string str = lua_tostring(this->_st, -1);
    lua_pop(this->_st, 1);
    return str;
}
Exemplo n.º 10
0
  void LuaContext::GetJson(Json::Value& result,
                           int top)
  {
    if (lua_istable(lua_, top))
    {
      Json::Value tmp = Json::objectValue;
      bool isArray = true;
      size_t size = 0;

      // Code adapted from: http://stackoverflow.com/a/6142700/881731
      
      // Push another reference to the table on top of the stack (so we know
      // where it is, and this function can work for negative, positive and
      // pseudo indices
      lua_pushvalue(lua_, top);
      // stack now contains: -1 => table
      lua_pushnil(lua_);
      // stack now contains: -1 => nil; -2 => table
      while (lua_next(lua_, -2))
      {
        // stack now contains: -1 => value; -2 => key; -3 => table
        // copy the key so that lua_tostring does not modify the original
        lua_pushvalue(lua_, -2);
        // stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
        std::string key(lua_tostring(lua_, -1));
        Json::Value v;
        GetJson(v, -2);

        tmp[key] = v;

        size += 1;
        try
        {
          if (boost::lexical_cast<size_t>(key) != size)
          {
            isArray = false;
          }
        }
        catch (boost::bad_lexical_cast&)
        {
          isArray = false;
        }
        
        // pop value + copy of key, leaving original key
        lua_pop(lua_, 2);
        // stack now contains: -1 => key; -2 => table
      }
      // stack now contains: -1 => table (when lua_next returns 0 it pops the key
      // but does not push anything.)
      // Pop table
      lua_pop(lua_, 1);

      // Stack is now the same as it was on entry to this function

      if (isArray)
      {
        result = Json::arrayValue;
        for (size_t i = 0; i < size; i++)
        {
          result.append(tmp[boost::lexical_cast<std::string>(i + 1)]);
        }
      }
      else
      {
        result = tmp;
      }
    }
    else if (lua_isnil(lua_, top))
    {
      result = Json::nullValue;
    }
    else if (lua_isboolean(lua_, top))
    {
      result = lua_toboolean(lua_, top) ? true : false;
    }
    else if (lua_isnumber(lua_, top))
    {
      // Convert to "int" if truncation does not loose precision
      double value = static_cast<double>(lua_tonumber(lua_, top));
      int truncated = static_cast<int>(value);

      if (std::abs(value - static_cast<double>(truncated)) <= 
          std::numeric_limits<double>::epsilon())
      {
        result = truncated;
      }
      else
      {
        result = value;
      }
    }
    else if (lua_isstring(lua_, top))
    {
      // Caution: The "lua_isstring()" case must be the last, since
      // Lua can convert most types to strings by default.
      result = std::string(lua_tostring(lua_, top));
    }
    else
    {
      LOG(WARNING) << "Unsupported Lua type when returning Json";
      result = Json::nullValue;
    }
  }
Exemplo n.º 11
0
static int _load_script(void)
{
	int rc = SLURM_SUCCESS;
	struct stat st;
	lua_State *L_orig = L;

	if (stat(lua_script_path, &st) != 0) {
		if (L_orig) {
			(void) error("Unable to stat %s, "
			             "using old script: %s",
			             lua_script_path, strerror(errno));
			return SLURM_SUCCESS;
		}
		return error("Unable to stat %s: %s",
		             lua_script_path, strerror(errno));
	}
	
	if (st.st_mtime <= lua_script_last_loaded) {
		return SLURM_SUCCESS;
	}

	/*
	 *  Initilize lua
	 */
	L = luaL_newstate();
	luaL_openlibs(L);
	if (luaL_loadfile(L, lua_script_path)) {
		if (L_orig) {
			(void) error("lua: %s: %s, using previous script",
			             lua_script_path, lua_tostring(L, -1));
			lua_close(L);
			L = L_orig;
			return SLURM_SUCCESS;
		}
		rc = error("lua: %s: %s", lua_script_path,
		           lua_tostring(L, -1));
		lua_pop(L, 1);
		return rc;
	}

	/*
	 *  Register SLURM functions in lua state:
	 *  logging and slurm structure read/write functions
	 */
	_register_lua_slurm_output_functions();
	_register_lua_slurm_struct_functions();

	/*
	 *  Run the user script:
	 */
	if (lua_pcall(L, 0, 1, 0) != 0) {
		if (L_orig) {
			(void) error("job_submit/lua: %s: %s, "
			             "using previous script",
			             lua_script_path, lua_tostring(L, -1));
			lua_close(L);
			L = L_orig;
			return SLURM_SUCCESS;
		}
		rc = error("job_submit/lua: %s: %s",
		           lua_script_path, lua_tostring(L, -1));
		lua_pop(L, 1);
		return rc;
	}

	/*
	 *  Get any return code from the lua script
	 */
	rc = (int) lua_tonumber(L, -1);
	if (rc != SLURM_SUCCESS) {
		if (L_orig) {
			(void) error("job_submit/lua: %s: returned %d "
			             "on load, using previous script",
			             lua_script_path, rc);
			lua_close(L);
			L = L_orig;
			return SLURM_SUCCESS;
		}
		(void) error("job_submit/lua: %s: returned %d on load",
		             lua_script_path, rc);
		lua_pop (L, 1);
		return rc;
	}

	/*
	 *  Check for required lua script functions:
	 */
	rc = _check_lua_script_functions();
	if (rc != SLURM_SUCCESS) {
		if (L_orig) {
			(void) error("job_submit/lua: %s: "
			             "required function(s) not present, "
			             "using previous script",
			             lua_script_path);
			lua_close(L);
			L = L_orig;
			return SLURM_SUCCESS;
		}
		return rc;
	}

	if (L_orig)
		lua_close(L_orig);
	lua_script_last_loaded = time(NULL);
	return SLURM_SUCCESS;
}
Exemplo n.º 12
0
void LuaParser::ReloadQuests() {
	loaded_.clear();
	errors_.clear();
	lua_encounter_events_registered.clear();
	lua_encounters_loaded.clear();

	for (auto encounter : lua_encounters) {
		encounter.second->Depop();
	}
	lua_encounters.clear();

	if(L) {
		lua_close(L);
	}

	L = luaL_newstate();
	luaL_openlibs(L);

	if(luaopen_bit(L) != 1) {
		std::string error = lua_tostring(L, -1);
		AddError(error);
	}

	if(luaL_dostring(L, "math.randomseed(os.time())")) {
		std::string error = lua_tostring(L, -1);
		AddError(error);
	}

#ifdef SANITIZE_LUA_LIBS
	//io
	lua_pushnil(L);
	lua_setglobal(L, "io");

	//some os/debug are okay some are not
	lua_getglobal(L, "os");
	lua_pushnil(L);
	lua_setfield(L, -2, "exit");
	lua_pushnil(L);
	lua_setfield(L, -2, "execute");
	lua_pushnil(L);
	lua_setfield(L, -2, "getenv");
	lua_pushnil(L);
	lua_setfield(L, -2, "remove");
	lua_pushnil(L);
	lua_setfield(L, -2, "rename");
	lua_pushnil(L);
	lua_setfield(L, -2, "setlocale");
	lua_pushnil(L);
	lua_setfield(L, -2, "tmpname");
	lua_pop(L, 1);

	lua_pushnil(L);
	lua_setglobal(L, "collectgarbage");

	lua_pushnil(L);
	lua_setglobal(L, "loadfile");

#endif

	// lua 5.2+ defines these
#if defined(LUA_VERSION_MAJOR) && defined(LUA_VERSION_MINOR)
	const char lua_version[] = LUA_VERSION_MAJOR "." LUA_VERSION_MINOR;
#elif LUA_VERSION_NUM == 501
	const char lua_version[] = "5.1";
#else
#error Incompatible lua version
#endif

#ifdef WINDOWS
	const char libext[] = ".dll";
#else
	// lua doesn't care OSX doesn't use sonames
	const char libext[] = ".so";
#endif

	lua_getglobal(L, "package");
	lua_getfield(L, -1, "path");
	std::string module_path = lua_tostring(L,-1);
	module_path += ";./" + Config->LuaModuleDir + "?.lua;./" + Config->LuaModuleDir + "?/init.lua";
	// luarock paths using lua_modules as tree
	// to path it adds foo/share/lua/5.1/?.lua and foo/share/lua/5.1/?/init.lua
	module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?.lua";
	module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?/init.lua";
	lua_pop(L, 1);
	lua_pushstring(L, module_path.c_str());
	lua_setfield(L, -2, "path");
	lua_pop(L, 1);

	lua_getglobal(L, "package");
	lua_getfield(L, -1, "cpath");
	module_path = lua_tostring(L, -1);
	module_path += ";./" + Config->LuaModuleDir + "?" + libext;
	// luarock paths using lua_modules as tree
	// luarocks adds foo/lib/lua/5.1/?.so for cpath
	module_path += ";./" + Config->LuaModuleDir + "lib/lua/" + lua_version + "/?" + libext;
	lua_pop(L, 1);
	lua_pushstring(L, module_path.c_str());
	lua_setfield(L, -2, "cpath");
	lua_pop(L, 1);

	MapFunctions(L);

	//load init
	std::string path = Config->QuestDir;
	path += "/";
	path += QUEST_GLOBAL_DIRECTORY;
	path += "/script_init.lua";

	FILE *f = fopen(path.c_str(), "r");
	if(f) {
		fclose(f);

		if(luaL_dofile(L, path.c_str())) {
			std::string error = lua_tostring(L, -1);
			AddError(error);
		}
	}

	//zone init - always loads after global
	if(zone) {
		std::string zone_script = Config->QuestDir;
		zone_script += "/";
		zone_script += zone->GetShortName();
		zone_script += "/script_init_v";
		zone_script += std::to_string(zone->GetInstanceVersion());
		zone_script += ".lua";
		f = fopen(zone_script.c_str(), "r");
		if(f) {
			fclose(f);

			if(luaL_dofile(L, zone_script.c_str())) {
				std::string error = lua_tostring(L, -1);
				AddError(error);
			}

			return;
		}

		zone_script = Config->QuestDir;
		zone_script += "/";
		zone_script += zone->GetShortName();
		zone_script += "/script_init.lua";
		f = fopen(zone_script.c_str(), "r");
		if(f) {
			fclose(f);

			if(luaL_dofile(L, zone_script.c_str())) {
				std::string error = lua_tostring(L, -1);
				AddError(error);
			}
		}
	}
}
Exemplo n.º 13
0
int LuaParser::_EventSpell(std::string package_name, QuestEventID evt, NPC* npc, Client *client, uint32 spell_id, uint32 extra_data,
						   std::vector<EQEmu::Any> *extra_pointers, luabind::adl::object *l_func) {
	const char *sub_name = LuaEvents[evt];

	int start = lua_gettop(L);

	try {
		int npop = 1;
		if(l_func != nullptr) {
			l_func->push(L);
		} else {
			lua_getfield(L, LUA_REGISTRYINDEX, package_name.c_str());
			lua_getfield(L, -1, sub_name);
			npop = 2;
		}

		lua_createtable(L, 0, 0);

		//always push self even if invalid
		if(IsValidSpell(spell_id)) {
			Lua_Spell l_spell(&spells[spell_id]);
			luabind::adl::object l_spell_o = luabind::adl::object(L, l_spell);
			l_spell_o.push(L);
		} else {
			Lua_Spell l_spell(nullptr);
			luabind::adl::object l_spell_o = luabind::adl::object(L, l_spell);
			l_spell_o.push(L);
		}
		lua_setfield(L, -2, "self");

		auto arg_function = SpellArgumentDispatch[evt];
		arg_function(this, L, npc, client, spell_id, extra_data, extra_pointers);

		quest_manager.StartQuest(npc, client, nullptr);
		if(lua_pcall(L, 1, 1, 0)) {
			std::string error = lua_tostring(L, -1);
			AddError(error);
			quest_manager.EndQuest();
			return 0;
		}
		quest_manager.EndQuest();

		if(lua_isnumber(L, -1)) {
			int ret = static_cast<int>(lua_tointeger(L, -1));
			lua_pop(L, npop);
			return ret;
		}

		lua_pop(L, npop);
	} catch(std::exception &ex) {
		std::string error = "Lua Exception: ";
		error += std::string(ex.what());
		AddError(error);

		//Restore our stack to the best of our ability
		int end = lua_gettop(L);
		int n = end - start;
		if(n > 0) {
			lua_pop(L, n);
		}
	}

	return 0;
}
Exemplo n.º 14
0
int LuaParser::_EventItem(std::string package_name, QuestEventID evt, Client *client, EQEmu::ItemInstance *item, Mob *mob,
						  std::string data, uint32 extra_data, std::vector<EQEmu::Any> *extra_pointers, luabind::adl::object *l_func) {
	const char *sub_name = LuaEvents[evt];

	int start = lua_gettop(L);

	try {
		int npop = 1;
		if(l_func != nullptr) {
			l_func->push(L);
		} else {
			lua_getfield(L, LUA_REGISTRYINDEX, package_name.c_str());
			lua_getfield(L, -1, sub_name);
		}

		lua_createtable(L, 0, 0);
		//always push self
		Lua_ItemInst l_item(item);
		luabind::adl::object l_item_o = luabind::adl::object(L, l_item);
		l_item_o.push(L);
		lua_setfield(L, -2, "self");

		Lua_Client l_client(client);
		luabind::adl::object l_client_o = luabind::adl::object(L, l_client);
		l_client_o.push(L);
		lua_setfield(L, -2, "owner");

		//redo this arg function
		auto arg_function = ItemArgumentDispatch[evt];
		arg_function(this, L, client, item, mob, data, extra_data, extra_pointers);

		quest_manager.StartQuest(client, client, item);
		if(lua_pcall(L, 1, 1, 0)) {
			std::string error = lua_tostring(L, -1);
			AddError(error);
			quest_manager.EndQuest();
			return 0;
		}
		quest_manager.EndQuest();

		if(lua_isnumber(L, -1)) {
			int ret = static_cast<int>(lua_tointeger(L, -1));
			lua_pop(L, npop);
			return ret;
		}

		lua_pop(L, npop);
	} catch(std::exception &ex) {
		std::string error = "Lua Exception: ";
		error += std::string(ex.what());
		AddError(error);

		//Restore our stack to the best of our ability
		int end = lua_gettop(L);
		int n = end - start;
		if(n > 0) {
			lua_pop(L, n);
		}
	}

	return 0;
}
Exemplo n.º 15
0
int CLuaFunctionDefs::OutputDebugString ( lua_State* luaVM )
{
    SString strMessage;
    unsigned int uiLevel;
    unsigned char ucR, ucG, ucB;

    CScriptArgReader argStream ( luaVM );
    argStream.ReadAnyAsString( strMessage );
    argStream.ReadNumber ( uiLevel, 3 );

    if ( uiLevel == 0 )
    {
        argStream.ReadNumber ( ucR, 0xFF );
        argStream.ReadNumber ( ucG, 0xFF );
        argStream.ReadNumber ( ucB, 0xFF );
    }

    if ( !argStream.HasErrors () )
    {
        if ( uiLevel > 3 )
        {
            m_pScriptDebugging->LogWarning ( luaVM, "Bad level argument sent to %s (0-3)", lua_tostring ( luaVM, lua_upvalueindex ( 1 ) ) );

            lua_pushboolean ( luaVM, false );
            return 1;
        }

        if ( uiLevel == 1 )
        {
            m_pScriptDebugging->LogError ( luaVM, "%s", strMessage.c_str () );
        }
        else if ( uiLevel == 2 )
        {
            m_pScriptDebugging->LogWarning ( luaVM, "%s", strMessage.c_str () );
        }
        else if ( uiLevel == 3 )
        {
            m_pScriptDebugging->LogInformation ( luaVM, "%s", strMessage.c_str () );
        }
        else if ( uiLevel == 0 )
        {
            m_pScriptDebugging->LogCustom ( luaVM, ucR, ucG, ucB, "%s", strMessage.c_str () );
        }
        lua_pushboolean ( luaVM, true );
        return 1;
    }
    else
        m_pScriptDebugging->LogCustom ( luaVM, argStream.GetFullErrorMessage () );

    lua_pushboolean ( luaVM, false );
    return 1;
}
Exemplo n.º 16
0
char * Encrypt(char *usr,char * password,int num,char * encfile)
{
    char username[128];
    strcpy(username,usr);
    UCase(username);
    int iError = 0,n,i,j;
    unsigned short nRand = 0,nSum = 0,nKey = 0;
    char cTmp[256];
    char Encrypt_str[256] = "";
    const char *Encrypt_str1;
    //播种
    srand((unsigned)time(0));
    //随机数
    nRand = rand();
    for (n = 0; n < num ; ++n)
    {
        nRand++;
        nSum = 0;
        for (i = 0; i <strlen(password); i++)
        {
            nSum += password[i];
        }
        nKey = nSum ^ nRand;

        //初始化lua
        lua_State *L = lua_open();
        //载入lua标准库
        luaL_openlibs(L);
        //注册函数
        lua_enc_bit(L);
        //载入执行脚本
        iError = luaL_loadfile(L,encfile);
        if (iError)
        {
            printf("Load script FAILED! %s",lua_tostring(L, -1));
            lua_close(L);
            return "";
        }
        iError = lua_pcall(L, 0, 0, 0);
        if (iError)
        {
            printf("Run FAILED! %s",lua_tostring(L, -1));
            lua_close(L);
            return "";
        }
        //通过函数名取出函数地址压入栈
        lua_getglobal( L,"xxx");
        lua_pushstring(L,username);
        lua_pushstring(L,password);
        lua_pushnumber(L,nRand);
        iError = lua_pcall(L, 3, 1, 0);
        if (iError)
        {
            printf("Run FAILED! %s",lua_tostring(L, -1));
            lua_close(L);
            return "";
        }
        if (lua_isstring(L, -1) )
        {
            Encrypt_str1 = lua_tostring(L, -1);





        }
        else
        {
            printf("Return Wrong\n");
        }
        strcpy(Encrypt_str,Encrypt_str1);
        lua_close(L);
        sprintf(cTmp,"%04x",nKey);
//		printf("%s\n",cTmp);
        for (j = 0; j < 4; j++)
        {
            Encrypt_str[j+28] = cTmp[j];
        }
        printf("~ghca%s\n",Encrypt_str);

    }
    return Encrypt_str;
}
Exemplo n.º 17
0
static int lua_iso8583_new(lua_State *L)
{
	struct iso8583 *iso8583h;
	iso8583_userdata *iso8583u = (iso8583_userdata *)lua_newuserdata(L, sizeof(iso8583_userdata));
	char error[BUFSIZ];

	iso8583u->handle = NULL;

	luaL_getmetatable(L, "iso8583");
	lua_setmetatable(L, -2);

	iso8583h = iso8583u->handle = iso8583_create();

	if (!iso8583h) {
		lua_pushnil(L);
		lua_pushstring(L, "alloc memory failed!");
		return 2;
	}

    if (lua_istable(L, 1)) {
    	lua_pushnil(L);  
		while (lua_next(L, 1) != 0)	{
			if (lua_isnumber(L, -2)) {
				int i = lua_tointeger(L, -2);

				if (i >= 0 && i <= 128) {
					if (lua_istable(L, -1)) {
						int size;
						int type;
						int align;
						int compress;
						char pad;
						
						// get size
						lua_getfield(L, -1, "size");
						
						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the size is not a number!", i);
							lua_pushstring(L, error);
							return 2;
						}

						size = lua_tointeger(L, -1);

						if (size < 0) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the size is little then 0! size = %d", i, size);
							lua_pushstring(L, error);
							return 2;
						}

						lua_pop(L, 1);

						// get type
						lua_getfield(L, -1, "type");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the type is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						type = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get align;
						lua_getfield(L, -1, "align");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the align is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						align = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get compress;
						lua_getfield(L, -1, "compress");

						if (!lua_isnumber(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the compress is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						compress = lua_tointeger(L, -1);

						lua_pop(L, 1);

						// get pad;
						lua_getfield(L, -1, "pad");

						if (!lua_isstring(L, -1) || !lua_objlen(L, -1)) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %d error! the pad is invalid!", i);
							lua_pushstring(L, error);
							return 2;
						}
						
						pad = *lua_tostring(L, -1);

						lua_pop(L, 1);

						// define field
						if (iso8583_define(iso8583h, i, (unsigned int)size, pad, (unsigned int)type, 
											(unsigned int)align, (unsigned int)compress) != ISO8583_OK) {
							lua_pushnil(L);
							snprintf(error, BUFSIZ, "field %u error! the field is invalid! size = %u, "
													"pad = %c, type = %u, align = %u, compress = %u!", 
										i, size, pad, type, align, compress);
							lua_pushstring(L, error);
							return 2;
						}
					}
				}
			}
			lua_pop(L, 1);
		}
	}

    return 1;
}
Exemplo n.º 18
0
/**
 * @brief Mods player using the power of Lua.
 */
static void faction_modPlayerLua( int f, double mod, const char *source, int secondary )
{
   Faction *faction;
   lua_State *L;
   int errf;
   double old, delta;
   HookParam hparam[3];

   faction = &faction_stack[f];

   /* Make sure it's not static. */
   if (faction_isFlag(faction, FACTION_STATIC))
      return;

   L     = faction->state;
   old   = faction->player;

   if (L == NULL)
      faction->player += mod;
   else {
#if DEBUGGING
      lua_pushcfunction(L, nlua_errTrace);
      errf = -6;
#else /* DEBUGGING */
      errf = 0;
#endif /* DEBUGGING */

      /* Set up the function:
       * faction_hit( current, amount, source, secondary ) */
      lua_getglobal(   L, "faction_hit" );
      lua_pushnumber(  L, faction->player );
      lua_pushnumber(  L, mod );
      lua_pushstring(  L, source );
      lua_pushboolean( L, secondary );

      /* Call function. */
      if (lua_pcall( L, 4, 1, errf )) { /* An error occurred. */
         WARN("Faction '%s': %s", faction->name, lua_tostring(L,-1));
#if DEBUGGING
         lua_pop( L, 2 );
#else /* DEBUGGING */
         lua_pop( L, 1 );
#endif /* DEBUGGING */
         return;
      }

      /* Parse return. */
      if (!lua_isnumber( L, -1 ))
         WARN( "Lua script for faction '%s' did not return a number from 'faction_hit(...)'.", faction->name );
      else
         faction->player = lua_tonumber( L, -1 );
#if DEBUGGING
      lua_pop( L, 2 );
#else /* DEBUGGING */
      lua_pop( L, 1 );
#endif /* DEBUGGING */
   }

   /* Sanitize just in case. */
   faction_sanitizePlayer( faction );

   /* Run hook if necessary. */
   delta = faction->player - old;
   if (fabs(delta) > 1e-10) {
      hparam[0].type    = HOOK_PARAM_FACTION;
      hparam[0].u.lf.f  = f;
      hparam[1].type    = HOOK_PARAM_NUMBER;
      hparam[1].u.num   = delta;
      hparam[2].type    = HOOK_PARAM_SENTINEL;
      hooks_runParam( "standing", hparam );

      /* Tell space the faction changed. */
      space_factionChange();
   }
}
Exemplo n.º 19
0
static int
_panic(lua_State *L) {
	const char * err = lua_tostring(L,-1);
	fault("%s", err);
	return 0;
}
Exemplo n.º 20
0
/**
 * @brief Parses a single faction, but doesn't set the allies/enemies bit.
 *
 *    @param temp Faction to load data into.
 *    @param parent Parent node to extract faction from.
 *    @return Faction created from parent node.
 */
static int faction_parse( Faction* temp, xmlNodePtr parent )
{
   xmlNodePtr node;
   int player;
   char buf[PATH_MAX], *dat, *ctmp;
   glColour *col;
   uint32_t ndat;

   /* Clear memory. */
   memset( temp, 0, sizeof(Faction) );

   temp->name = xml_nodeProp(parent,"name");
   if (temp->name == NULL)
      WARN("Faction from "FACTION_DATA_PATH" has invalid or no name");

   player = 0;
   node = parent->xmlChildrenNode;
   do {

      /* Only care about nodes. */
      xml_onlyNodes(node);

      /* Can be 0 or negative, so we have to take that into account. */
      if (xml_isNode(node,"player")) {
         temp->player_def = xml_getFloat(node);
         player = 1;
         continue;
      }

      xmlr_strd(node,"longname",temp->longname);
      xmlr_strd(node,"display",temp->displayname);
      if (xml_isNode(node, "colour")) {
         ctmp = xml_getStrd(node);
         if (ctmp != NULL)
            temp->colour = col_fromName(xml_raw(node));
         /* If no named colour is present, RGB attributes are used. */
         else {
            /* Initialize in case a colour channel is absent. */
            col = calloc( 1, sizeof(glColour*) );

            xmlr_attr(node,"r",ctmp);
            if (ctmp != NULL) {
               col->r = atof(ctmp);
               free(ctmp);
            }

            xmlr_attr(node,"g",ctmp);
            if (ctmp != NULL) {
               col->g = atof(ctmp);
               free(ctmp);
            }

            xmlr_attr(node,"b",ctmp);
            if (ctmp != NULL) {
               col->b = atof(ctmp);
               free(ctmp);
            }

            col->a = 1.;
            temp->colour = col;
         }
         continue;
      }

      if (xml_isNode(node, "spawn")) {
         if (temp->sched_state != NULL)
            WARN("Faction '%s' has duplicate 'spawn' tag.", temp->name);
         nsnprintf( buf, sizeof(buf), "dat/factions/spawn/%s.lua", xml_raw(node) );
         temp->sched_state = nlua_newState();
         nlua_loadStandard( temp->sched_state, 0 );
         dat = ndata_read( buf, &ndat );
         if (luaL_dobuffer(temp->sched_state, dat, ndat, buf) != 0) {
            WARN("Failed to run spawn script: %s\n"
                  "%s\n"
                  "Most likely Lua file has improper syntax, please check",
                  buf, lua_tostring(temp->sched_state,-1));
            lua_close( temp->sched_state );
            temp->sched_state = NULL;
         }
         free(dat);
         continue;
      }

      if (xml_isNode(node, "standing")) {
         if (temp->state != NULL)
            WARN("Faction '%s' has duplicate 'standing' tag.", temp->name);
         nsnprintf( buf, sizeof(buf), "dat/factions/standing/%s.lua", xml_raw(node) );
         temp->state = nlua_newState();
         nlua_loadStandard( temp->state, 0 );
         dat = ndata_read( buf, &ndat );
         if (luaL_dobuffer(temp->state, dat, ndat, buf) != 0) {
            WARN("Failed to run standing script: %s\n"
                  "%s\n"
                  "Most likely Lua file has improper syntax, please check",
                  buf, lua_tostring(temp->state,-1));
            lua_close( temp->state );
            temp->state = NULL;
         }
         free(dat);
         continue;
      }

      if (xml_isNode(node, "known")) {
         faction_setFlag(temp, FACTION_KNOWN);
         continue;
      }

      if (xml_isNode(node, "equip")) {
         if (temp->equip_state != NULL)
            WARN("Faction '%s' has duplicate 'equip' tag.", temp->name);
         nsnprintf( buf, sizeof(buf), "dat/factions/equip/%s.lua", xml_raw(node) );
         temp->equip_state = nlua_newState();
         nlua_loadStandard( temp->equip_state, 0 );
         dat = ndata_read( buf, &ndat );
         if (luaL_dobuffer(temp->equip_state, dat, ndat, buf) != 0) {
            WARN("Failed to run equip script: %s\n"
                  "%s\n"
                  "Most likely Lua file has improper syntax, please check",
                  buf, lua_tostring(temp->equip_state,-1));
            lua_close( temp->equip_state );
            temp->equip_state = NULL;
         }
         free(dat);
         continue;
      }

      if (xml_isNode(node,"logo")) {
         if (temp->logo_small != NULL)
            WARN("Faction '%s' has duplicate 'logo' tag.", temp->name);
         nsnprintf( buf, PATH_MAX, FACTION_LOGO_PATH"%s_small.png", xml_get(node));
         temp->logo_small = gl_newImage(buf, 0);
         nsnprintf( buf, PATH_MAX, FACTION_LOGO_PATH"%s_tiny.png", xml_get(node));
         temp->logo_tiny = gl_newImage(buf, 0);
         continue;
      }

      if (xml_isNode(node,"static")) {
         faction_setFlag(temp, FACTION_STATIC);
         continue;
      }

      if (xml_isNode(node,"invisible")) {
         faction_setFlag(temp, FACTION_INVISIBLE);
         continue;
      }

      /* Avoid warnings. */
      if (xml_isNode(node,"allies") || xml_isNode(node,"enemies"))
         continue;

      DEBUG("Unknown node '%s' in faction '%s'",node->name,temp->name);
   } while (xml_nextNode(node));

   if (player==0)
      DEBUG("Faction '%s' missing player tag.", temp->name);
   if ((temp->state!=NULL) && faction_isFlag( temp, FACTION_STATIC ))
      WARN("Faction '%s' has Lua and is static!", temp->name);
   if ((temp->state==NULL) && !faction_isFlag( temp, FACTION_STATIC ))
      WARN("Faction '%s' has no Lua and isn't static!", temp->name);

   return 0;
}
Exemplo n.º 21
0
//Lua argument getters
item_id item_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_item_data, lua_tostring(L, idx));
}
Exemplo n.º 22
0
INT_PTR ACheatInfoDlg::OnCommand(int codeNotify,int ctrlID,HWND hWndCtrl)
{
	if(hWndCtrl){
		if(ctrlID == IDC_CHEAT_EXECLUA){
			int isel = m_CheatsList->GetNextItem(-1,LVNI_SELECTED);
			if(isel==-1){
				this->MessageBox("选中一个值先~");
				return 0;
			}

			extern FCEUGI *GameInfo;
			if(!GameInfo){
				MessageBox("请先打开游戏~","",MB_ICONINFORMATION);
				return 0;
			}

			std::string& str = m_pEntry->item.values[isel]->script;
			int error = luaL_loadbuffer((lua_State*)luastate,str.c_str(),str.size(),"") 
				|| lua_pcall((lua_State*)luastate,0,0,0);

			if(error != 0){
				//fprintf(stderr,"lua_pcall() error:%s\n",lua_tostring(L,-1));
				this->MessageBox(lua_tostring((lua_State*)luastate,-1),"lua脚本错误",MB_ICONERROR);
				lua_pop((lua_State*)luastate,1);
			}
			return 0;
		}else if(ctrlID == IDC_CHEAT_CHEATINFO){
			ACheatCheatInfoDlg dlg(this,m_pEntry);
			if(dlg.GetDlgCode() == IDOK){
				m_editName->SetWindowText(m_pEntry->item.name.c_str());
				
				ControlMessage cm = {0};
				cm.self = this;
				cm.uMsg = WM_SETTEXT;
				cm.wParam = (WPARAM)m_pEntry->item.name.c_str();
				NotifyParent(&cm);
				m_pFile->bNeedSaving = true;
				return SetDlgResult(TRUE);
			}
			return 0;
		}else if(ctrlID == IDC_CHEAT_EDITSCRIPT){
			int isel = m_CheatsList->GetNextItem(-1,LVNI_SELECTED);
			if(isel==-1){
				this->MessageBox("选中一个值先~");
				return 0;
			}
			ACheatEntry::VALUE* v = m_pEntry->item.values[isel];
			AEditCheatDlg dlg(this,(char*)v->name.c_str(),(char*)v->script.c_str());
			int code = dlg.GetDlgCode();
			if(code == AEditCheatDlg::RET_CLOSE || code==AEditCheatDlg::RET_CANCEL){

			}else if(code == AEditCheatDlg::RET_OK){
				std::string& name = dlg.GetName();
				std::string& script = dlg.GetScript();

				v->name = name;
				v->script = script;

				UpdateListItem(isel,v->name.c_str(),0);
				m_pFile->bNeedSaving = true;
				return 0;
			}
			return 0;
		}else if(ctrlID == IDC_CHEAT_ADDLUA){
			AEditCheatDlg dlg(this);
			int code = dlg.GetDlgCode();
			if(code == AEditCheatDlg::RET_CLOSE || code==AEditCheatDlg::RET_CANCEL){

			}else if(code == AEditCheatDlg::RET_OK){
				std::string& name = dlg.GetName();
				std::string& script = dlg.GetScript();
				ACheatEntry::VALUE* pValue = new ACheatEntry::VALUE;
				pValue->name = name;
				pValue->script = script;
				m_pEntry->item.values.push_back(pValue);
				AddListItem(pValue->name.c_str(),0);
				m_pFile->bNeedSaving = true;
				return 0;
			}
			return 0;
		}else if(ctrlID == IDC_CHEAT_DELETELUA){
			int count_selected = 0;
			int i;
			for(i=-1;(i=m_CheatsList->GetNextItem(i,LVNI_SELECTED))!=-1;){
				count_selected++;
			}
			if(count_selected == 0){
				MessageBox("选择至少一个要删除的值~","",MB_ICONINFORMATION);
				return SetDlgResult(FALSE);
			}else{
				stringstream ss;
				ss<<"删除选中的 "<<count_selected<<" 项?";
				string str = ss.str();
				if(MessageBox(str.c_str(),"确认",MB_OKCANCEL|MB_ICONQUESTION) == IDCANCEL){
					return SetDlgResult(FALSE);
				}
			}

			for(i=-1;(i=m_CheatsList->GetNextItem(i,LVNI_SELECTED))!=-1;){
				m_CheatsList->DeleteItem(i);
				auto& vs = m_pEntry->item.values;
				auto v = vs[i];
				delete v;

				auto s=vs.begin();
				for(; *s != v; ++s)
					;
				vs.erase(s);
				i--;
			}
			m_pFile->bNeedSaving = true;

			return SetDlgResult(TRUE);
		}else if(ctrlID == IDC_CHEAT_CUSTOM){
			lua_State* L = (lua_State*)luastate;
			
			bool need=false;
			for(string::size_type i=0;i<m_pEntry->item.custom.size(); i++){
				if(isalnum(m_pEntry->item.custom[i])){
					need = true;
					break;
				}
			}
			if(!need){
				MessageBox(
					"当前金手指未提供可自定义的脚本~"
					"\n\n"
					"你可以点击 '信息', 查看并修改自定义金手指脚本!",
					"金手指自定义",
					MB_ICONINFORMATION);
				return 0;
			}

			extern FCEUGI *GameInfo;
			if(!GameInfo){
				MessageBox("请先打开游戏~","",MB_ICONINFORMATION);
				return 0;
			}

			int ret=luaL_loadbuffer(L,m_pEntry->item.custom.c_str(),m_pEntry->item.custom.size(),"")
				||lua_pcall(L,0,0,0);
			if(ret != 0){
				this->MessageBox(lua_tostring(L,-1),"脚本错误",MB_ICONERROR);
				lua_pop(L,1);
			}
			return SetDlgResult(0);
		}
	}
	return 0;
}
Exemplo n.º 23
0
scriptobj_id scriptobject_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_scriptobject_data, lua_tostring(L, idx));
}
Exemplo n.º 24
0
static int attribute_lua_setfield(lua_State *L)
{
    attribute_lua_t *attribute = attribute_lua_check(L, 1);
    resource_lua_t *res = attribute->parent;
    resource_set_lua_t *rset = res->parent;
    mrp_attr_t attribute_list[MAX_ATTRS], *attrs, *orig;
    const char *key;
    int new_type;

    mrp_debug("> attribute_lua_setfield");

    /* attributes are indexed by string */

    if (lua_type(L, 2) != LUA_TSTRING)
        return luaL_error(L, "invalid attribute index type (needs to be string)");

    key = lua_tostring(L, 2);
    new_type = lua_type(L, 3);

    attrs = mrp_resource_set_read_all_attributes(rset->resource_set,
            res->resource_name, MAX_ATTRS-1, attribute_list);

    if (!attrs)
        return luaL_error(L, "internal resource library error");

    orig = attrs;

    while (attrs->name != NULL) {

        if (strcmp(attrs->name, key) == 0) {

            switch (attrs->type) {
                case mqi_string:
                    if (new_type != LUA_TSTRING)
                        return luaL_error(L, "type mismatch");
                    attrs->value.string = lua_tostring(L, 3);
                    break;
                case mqi_integer:
                {
                    int32_t i;
                    double dbl;

                    if (new_type != LUA_TNUMBER)
                        return luaL_error(L, "type mismatch");

                    if ((i = lua_tointeger(L, 3)) == (dbl = lua_tonumber(L, 3)))
                        attrs->value.integer = i;
                    else
                        return luaL_error(L, "type mismatch");

                    break;
                }
                case mqi_unsignd:
                {
                    int32_t i;
                    double dbl;

                    if (new_type != LUA_TNUMBER)
                        return luaL_error(L, "type mismatch");

                    if ((i = lua_tointeger(L, 3)) == (dbl = lua_tonumber(L, 3)) && i >= 0)
                        attrs->value.unsignd = i;
                    else
                        return luaL_error(L, "type mismatch");

                    break;
                }
                case mqi_floating:
                {
                    if (new_type != LUA_TNUMBER)
                        return luaL_error(L, "type mismatch");
                    attrs->value.floating = lua_tonumber(L, 3);
                    break;
                }
                default:
                    return luaL_error(L, "unhandled attribute type");
            }
            break; /* while */
        }

        attrs++;
    }

    mrp_resource_set_write_attributes(rset->resource_set, res->resource_name, orig);

    return 1;
}
Exemplo n.º 25
0
enemy_id enemy_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_enemy_data, lua_tostring(L, idx));
}
Exemplo n.º 26
0
static int resource_set_add_resource(lua_State *L)
{
    int narg;
    resource_set_lua_t *rset;
    resource_lua_t *resource;
    const char *resource_name;
    bool shared = FALSE;
    bool mandatory = TRUE;
    mrp_attr_t attribute_list[MAX_ATTRS], *attrs;

    mrp_debug("> add_resource");

    narg = lua_gettop(L);

    if (narg != 2)
        return luaL_error(L, "expecting one argument");

    rset = resource_set_lua_check(L, 1);

    if (!rset)
        goto error;

    /* the argument should be a table with at least "resource_name" index */

    if (!lua_istable(L, -1))
        return luaL_error(L, "argument error -- not a table");

    lua_pushstring(L, "resource_name");
    lua_gettable(L, -2);

    if (!lua_isstring(L, -1))
        return luaL_error(L, "'resource_name' is a mandatory field");

    resource_name = lua_tostring(L, -1);
    lua_pop(L, 1);

    lua_pushstring(L, "mandatory");
    lua_gettable(L, -2);

    if (lua_isboolean(L, -1)) {
        mandatory = lua_toboolean(L, -1);
    }
    lua_pop(L, 1);

    lua_pushstring(L, "shared");
    lua_gettable(L, -2);

    if (lua_isboolean(L, -1)) {
        shared = lua_toboolean(L, -1);
    }
    lua_pop(L, 1);

    /* create resource object and add it to the resource table in the resource
     * set object */

    resource = (resource_lua_t *) mrp_lua_create_object(L, RESOURCE_LUA_CLASS,
            NULL, 0);

    if (!resource)
        goto error;

    resource->mandatory = mandatory;
    resource->shared = shared;
    resource->acquired = FALSE;
    resource->available = FALSE;
    resource->resource_name = mrp_strdup(resource_name);

    if (!resource->resource_name)
        goto error;

    resource->parent = rset;
    resource->L = L;
    resource->ctx = rset->ctx;

    resource->real_attributes = (attribute_lua_t *) mrp_lua_create_object(L,
            ATTRIBUTE_LUA_CLASS, NULL, 0);
    resource->real_attributes->L = L;
    resource->real_attributes->ctx = rset->ctx;
    resource->real_attributes->parent = resource;
    resource->real_attributes->resource_set = rset;
    resource->real_attributes->initialized = TRUE;

    attrs = mrp_resource_set_read_all_attributes(rset->resource_set,
            resource->resource_name, MAX_ATTRS-1, attribute_list);

    if (mrp_resource_set_add_resource(rset->resource_set,
            resource->resource_name, shared, attrs, mandatory) < 0)
        goto error;

    /* add to resource map */

    mrp_htbl_insert(rset->resources, resource->resource_name, resource);

    return 1;

error:
    /* TODO: clean up the already allocated objects */

    return luaL_error(L, "internal resource library error");
}
Exemplo n.º 27
0
weapon_id weapon_from_lua(lua_State* L, int idx) {
	return get_X_by_name(game_weapon_data, lua_tostring(L, idx));
}
Exemplo n.º 28
0
static int resource_set_attributes(void *data, lua_State *L, int member, mrp_lua_value_t *v)
{
    resource_lua_t *res = (resource_lua_t *) data;
    resource_set_lua_t *rset = res->parent;
    mrp_attr_t attribute_list[MAX_ATTRS], *attrs, *orig;

    MRP_UNUSED(member);
    MRP_UNUSED(v);

    mrp_debug("> resource_set_attributes");

    if (!lua_istable(L, -1))
        return luaL_error(L, "argument error -- not a table");

    mrp_resource_set_read_all_attributes(rset->resource_set,
            res->resource_name, MAX_ATTRS-1, attribute_list);

    attrs = orig = attribute_list;

    while (attrs->name != NULL) {
        /* get the attribute from the lua table by name */

        lua_pushstring(L, attrs->name);
        lua_gettable(L, -2);

        /* update the attribute */

        switch (attrs->type) {
            case mqi_string:
                if (lua_isstring(L, -1)) {
                    attrs->value.string = lua_tostring(L, -1);
                    mrp_debug("updated attr '%s' to '%s'", attrs->name, attrs->value.string);
                }
                break;
            case mqi_integer:
                if (lua_isnumber(L, -1)) {
                    attrs->value.integer = lua_tointeger(L, -1);
                    mrp_debug("updated attr '%s' to '%i'", attrs->name, attrs->value.integer);
                }
                break;
            case mqi_unsignd:
                if (lua_isnumber(L, -1)) {
                    int val = lua_tointeger(L, -1);
                    if (val >= 0) {
                        attrs->value.unsignd = val;
                        mrp_debug("updated attr '%s' to '%u'", attrs->name, attrs->value.unsignd);
                    }
                }
                break;
            case mqi_floating:
                if (lua_isnumber(L, -1)) {
                    attrs->value.floating = lua_tonumber(L, -1);
                    mrp_debug("updated attr '%s' to '%f'", attrs->name, attrs->value.floating);
                }
                break;
            default:
                break;
        }

        lua_pop(L, 1);
        attrs++;
    }

    /* write the attributes back */
    mrp_resource_set_write_attributes(rset->resource_set, res->resource_name, orig);

    return 1;
}
Exemplo n.º 29
0
/*
 * Returns: processors_load_average (number), is_per_cpu (boolean)
 */
static int
sys_loadavg (lua_State *L)
{
  double loadavg;
#ifndef _WIN32
  const int res = 0;

  if (getloadavg(&loadavg, 1) == 1) {
    const int is_per_cpu = 1;
#else
  const int res = getloadavg(&loadavg);

  if (!res) {
    const int is_per_cpu = 0;
#endif
    lua_pushnumber(L, (lua_Number) loadavg);
    lua_pushboolean(L, is_per_cpu);
    return 2;
  }
  return sys_seterror(L, res);
}

/*
 * Arguments: [number_of_files (number)]
 * Returns: number_of_files (number)
 */
static int
sys_limit_nfiles (lua_State *L)
{
#ifndef _WIN32
  const int narg = lua_gettop(L);
  struct rlimit rlim;

  rlim.rlim_max = 0;
  getrlimit(RLIMIT_NOFILE, &rlim);
  lua_pushinteger(L, rlim.rlim_max);

  if (narg != 0) {
    const int n = lua_tointeger(L, 1);

    rlim.rlim_cur = rlim.rlim_max = n;
    if (setrlimit(RLIMIT_NOFILE, &rlim))
      return sys_seterror(L, 0);
  }
  return 1;
#else
  (void) L;

  lua_pushinteger(L, -1);
  return 1;
#endif
}

/*
 * Arguments: string
 * Returns: number
 */
static int
sys_toint (lua_State *L)
{
  const char *s = lua_tostring(L, 1);
  int num = 0, sign = 1;

  if (s) {
    switch (*s) {
    case '-': sign = -1;
    case '+': ++s;
    }
    while (*s >= '0' && *s <= '9')
      num = (num << 3) + (num << 1) + (*s++ & ~'0');
  }
  lua_pushinteger(L, sign * num);
  return 1;
}

/*
 * Arguments: error_handler (function), function, any ...
 * Returns: status (boolean), any ...
 */
static int
sys_xpcall (lua_State *L)
{
  const int status = lua_pcall(L, lua_gettop(L) - 2, LUA_MULTRET, 1);

  lua_pushboolean(L, !status);
  lua_insert(L, 2);
  return lua_gettop(L) - 1;
}


#include "isa/fcgi/sys_fcgi.c"
#include "mem/sys_mem.c"
#include "thread/sys_thread.c"

#ifndef _WIN32
#include "sys_unix.c"
#else
#include "win32/sys_win32.c"
#endif

#include "sys_file.c"
#include "sys_date.c"
#include "sys_env.c"
#include "sys_evq.c"
#include "sys_fs.c"
#include "sys_log.c"
#include "sys_proc.c"
#include "sys_rand.c"


static luaL_Reg sys_lib[] = {
  {"strerror",		sys_strerror},
  {"nprocs",		sys_nprocs},
  {"loadavg",		sys_loadavg},
  {"limit_nfiles",	sys_limit_nfiles},
  {"toint",		sys_toint},
  {"xpcall",		sys_xpcall},
  DATE_METHODS,
  ENV_METHODS,
  EVQ_METHODS,
  FCGI_METHODS,
  FD_METHODS,
  FS_METHODS,
  LOG_METHODS,
  PROC_METHODS,
  RAND_METHODS,
#ifndef _WIN32
  UNIX_METHODS,
#endif
  {NULL, NULL}
};


/*
 * Arguments: ..., sys_lib (table)
 */
static void
createmeta (lua_State *L)
{
  const int top = lua_gettop(L);
  const struct meta_s {
    const char *tname;
    luaL_Reg *meth;
    int is_index;
  } meta[] = {
    {DIR_TYPENAME,		dir_meth,	0},
    {EVQ_TYPENAME,		evq_meth,	1},
    {FD_TYPENAME,		fd_meth,	1},
    {PERIOD_TYPENAME,		period_meth,	1},
    {PID_TYPENAME,		pid_meth,	1},
    {LOG_TYPENAME,		log_meth,	0},
    {RAND_TYPENAME,		rand_meth,	0},
  };
  int i;

  for (i = 0; i < (int) (sizeof(meta) / sizeof(struct meta_s)); ++i) {
    luaL_newmetatable(L, meta[i].tname);
    if (meta[i].is_index) {
      lua_pushvalue(L, -1);  /* push metatable */
      lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
    }
    luaL_setfuncs(L, meta[i].meth, 0);
    lua_pop(L, 1);
  }

  /* Predefined file handles */
  luaL_getmetatable(L, FD_TYPENAME);
  {
    const char *std[] = {"stdin", "stdout", "stderr"};

    for (i = 3; i--; ) {
#ifndef _WIN32
      const fd_t fd = i;
#else
      const fd_t fd = GetStdHandle(i == 0 ? STD_INPUT_HANDLE
       : (i == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE));
#endif
      lua_pushstring(L, std[i]);
      lua_boxinteger(L, fd);
      lua_pushvalue(L, -3);  /* metatable */
      lua_pushboolean(L, 1);
      lua_rawseti(L, -2, (int) ((lua_Integer) fd));  /* don't close std. handles */
      lua_setmetatable(L, -2);
      lua_rawset(L, top);
    }
  }
  lua_settop(L, top);
}


LUALIB_API int
luaopen_sys (lua_State *L)
{
  luaL_register(L, LUA_SYSLIBNAME, sys_lib);
  createmeta(L);

  signal_init();

#ifdef _WIN32
  luaopen_sys_win32(L);
#endif
  luaopen_sys_mem(L);
  luaopen_sys_thread(L);

  return 1;
}
Exemplo n.º 30
0
bool read_schematic(lua_State *L, int index, DecoSchematic *dschem, Server *server) {
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	INodeDefManager *ndef = server->getNodeDefManager();

	if (lua_istable(L, index)) {
		lua_getfield(L, index, "size");
		v3s16 size = read_v3s16(L, -1);
		lua_pop(L, 1);
		
		int numnodes = size.X * size.Y * size.Z;
		MapNode *schemdata = new MapNode[numnodes];
		int i = 0;
		
		lua_getfield(L, index, "data");
		luaL_checktype(L, -1, LUA_TTABLE);
		
		lua_pushnil(L);
		while (lua_next(L, -2)) {
			if (i < numnodes) {
				// same as readnode, except param1 default is MTSCHEM_PROB_CONST
				lua_getfield(L, -1, "name");
				const char *name = luaL_checkstring(L, -1);
				lua_pop(L, 1);
				
				u8 param1;
				lua_getfield(L, -1, "param1");
				param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
				lua_pop(L, 1);
	
				u8 param2;
				lua_getfield(L, -1, "param2");
				param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
				lua_pop(L, 1);
				
				schemdata[i] = MapNode(ndef, name, param1, param2);
			}
			
			i++;
			lua_pop(L, 1);
		}
		
		dschem->size      = size;
		dschem->schematic = schemdata;
		
		if (i != numnodes) {
			errorstream << "read_schematic: incorrect number of "
				"nodes provided in raw schematic data (got " << i <<
				", expected " << numnodes << ")." << std::endl;
			return false;
		}
	} else if (lua_isstring(L, index)) {
		dschem->filename = std::string(lua_tostring(L, index));
	} else {
		errorstream << "read_schematic: missing schematic "
			"filename or raw schematic data" << std::endl;
		return false;
	}
	
	return true;
}