Tutorial: defining script calls that can reference by party index

An issue that I’ve come across often when writing event-related scripts is “how can I let the user check whether the leader satisfies some condition?”

For example, I want to check whether the leader is holding a shield. Well that’s easy I can just say

$game_party.leader.armors.any? {|armor| armor.etype_id == 1}Assuming etype 1 is the “shield” equip type. But this is not user-friendly: it means you need to know how to script. And what if you wanted to reference the second person in the party?There should be a better way to be able to do this, and the reason why I provide script call methods in the first place is so users don't need to worry about arrays or objects or zero-indexing or other things.

Suppose I were to write a convenience method in the game interpreter that checks whether a particular actor has a shield on

def shield_equipped?(actor_id) $game_actors[actor_id].armors.any?{|armor| armor.etype_id == 1}endPretty simple. But what about reference by party index? Let’s take advantage of the fact that when you are referencing database ID’s, they are all positive numbers. Why not use a negative number as a party index?
Code:
def shield_equipped?(party_index)  index = party_index.abs - 1  actor = $game_party.all_members[index]  return unless actor  actor.armors.any?{|armor| armor.etype_id == 1}end
This method assumes that the party index is negative. If you pass in -1, then it will retrieve the first actor in the party (index 0, since Ruby arrays are zero-indexed). Shouldn’t be too difficult for users to remember after awhile: just stick a negative sign in front of the ID.Now we can combine it together: you can search by actor ID, or party index:

Code:
def shield_equipped?(index)  # check party index if < 0  if index < 0    index = party_index.abs - 1    actor = $game_party.all_members[index]    return false unless actor    actor.armors.any?{|armor| armor.etype_id == 1}  else    $game_actors[index].armors.any?{|armor| armor.etype_id == 1 }  endend
Since you’ll probably be doing this often, it would be better to write it as its own method
Code:
def get_actor(index)  if index < 0    index = index.abs - 1    return $game_party.all_members[index]  else    return $game_actors[index]  endend
And now it is easy to write script calls for managing actors by ID and by party index
Code:
def shield_equipped?(index)  actor = get_actor(index)  return false unless actor  return actor.armors.any? {|armor| armor.etype_id == 1}end
Simply instruct your users to use a positive ID if they want to reference a specific actor, or use a negative ID if they want to reference by party index.

Original thread: https://forums.rpgmakerweb.com/threads/tutorial-defining-script-calls-that-can-reference-by-party-index.19390/