StendhalScripting/LuaAPI
The following objects & functions are exposed to the Lua engine:
Objects[编辑]
luajava[编辑]
This is an object of the LuajavaLib library. It can be used to coerce Java static objects to Lua or create new Java object instances.
Example of exposing a static object & enums to Lua:
-- store a Java enum in a Lua global variable
ConversationStates = luajava.bindClass("games.stendhal.server.entity.npc.ConversationStates")
-- access the enum values like so
ConversationStates.IDLE
Example of creating an object instance:
-- store instance in local variable
local dog = luajava.newInstance("games.stendhal.server.entity.npc.SilentNPC")
-- access object methods like so
dog:setEntityClass("animal/puppy")
dog:setPosition(2, 5)
-- class with constructor using parameters
local speaker = luajava.newInstance("games.stendhal.server.entity.npc.SpeakerNPC", "Frank")
speaker:setOutfit("body=0,head=0,eyes=0,hair=5,dress=5")
speaker:setPosition(2, 6)
To make scripting easier, Stendhal employs a Template:StendhalFile & some helper objects & methods to handle the functionality mentioned above. An explanation of these objects & methods follows.
logger[编辑]
Manages logging in Lua via the org.apache.log4j.Logger class.
Methods:
- logger:info(message)
- Prints an information level message to the console.
- message: Text to be printed.
- logger:warn(message)
- Prints a warning level message to the console.
- message: Text to be printed.
- logger:error(message)
- Prints an error level message to the console.
- message: Text to be printed.
Example usage:
local zone = "0_semos_city"
if game:setZone(zone) then
	-- do something
else
	logger:error("Could not set zone: " .. zone)
end
properties[编辑]
Defines functions for accessing Java system properties.
Methods:
- properties:getValue(p)
- Retrieves the value of a property.
- p: (string) Property name.
- returns: (string) Property value or `nil`.
- properties:enabled(p)
- Checks if a property is enabed.
- p: (string) Property name.
- returns: (boolean) `true` if enabled.
- properties:equals(p, v)
- Checks if a property is set to a specified value.
- p: (string) Property name.
- v: (string) Value to compare with.
- returns: (boolean) `true` if the value of the property is the same as `v`.
Examples usage:
-- example of only executing script contents on test server
if not properties:enabed("stendhal.testserver") then
    do return end
end
game[编辑]
The main object that handles setting zone & adding entities to game.
Methods:
- game:add(object)
- Adds an RPObject instance to the current zone.
- object: Object to add.
- game:add(npc)
- Adds an Template:StendhalFile instance to the current zone.
- npc: NPC to add.
- game:add(creature, x, y)
- Adds a Template:StendhalFile instance to the current zone.
- creature: Creature to add.
- x: Horizontal position of where to add creature.
- y: Vertical position of where to add creature.
- game:remove(object)
- object:
- game:remove(npc)
- npc:
- game:addGameEvent(source, event, params)
- Adds a new Template:StendhalFile.
- source:
- event:
- params:
- game:setZone(name)
- Sets the current zone.
- name: String identifier for zone to be set as current zone.
- returns: trueif zone was successfully set.
- game:setZone(zone)
- Sets the current zone.
- zone: Template:StendhalFile instance to set as current zone.
- returns: trueif zone was successfully set.
- game:getZone(object)
- Retrieves the zone where objectis located.
- object: The RPObject from which the zone should be retrieved.
- returns: Template:StendhalFile or nullif it doesn't exists
- game:getZone(name)
- Retrieves a zone by string ID.
- zoneName: Name of zone to retrieve.
- returns: Template:StendhalFile or nullif it doesn't exist.
- game:setMusic(filename, args)
- Sets the music for the currently selected zone.
- filename:
- File basename excluding .ogg extension.
- args:
- Lua table of key=value integer values.
- Valid keys:
- volume: Volume level (default: 100).
- x: The X coordinate of the sound source (default: 1).
- y: The Y coordinate of the sound source (default: 1).
- radius: The radius from which the music can be heard (default: 10000).
 
 
- game:playerIsInZone(player, zoneName)
- player:
- zoneName:
- returns: boolean
- game:getCreatures()
- returns: An array of all available creatures.
- game:getCreature(clazz)
- Retrieves a Template:StendhalFile instance.
- clazz: String name of the creature.
- returns: Creature or nullif doesn't exist.
- game:getItems()
- returns: Array list of available items.
- game:getItem(name)
- name:
- returns: Item instance or nullif doesn't exist.
- game:modify(entity)
- entity:
- game:privateText(player, text)
- Sends a private text to a player.
- player: Player to receive the message.
- text: Message text to send to player.
- game:getMessage()
- returns: String
entities[编辑]
See also: StendhalAPI#Entities for public methods that can be performed on Entity objects.
Methods:
- entities:getPlayer(name)
- Retrieves a logged in Player.
- name: (String) Name of player.
- returns: Logged in Template:StendhalFile or null.
- entities:getNPC(name)
- Retrieves an existing SpeakerNPC.
- name: (String) Name of NPC.
- returns: SpeakerNPC instance or null.
- entities:getItem(name)
- Retrieves a registered Item.
- name: (String) Name of the item.
- returns: Template:StendhalFile instance or nullif not a registered item.
- entities:getStackableItem(name)
- Retrieves a registered StackableItem.
- name: (String) Name of the item.
- returns: Template:StendhalFile instance or nullif not a registered stackable item.
- entities:createSpeakerNPC(name)
- Creates an interactive NPC.
- name: (String) Name of new NPC.
- returns: New SpeakerNPC instance.
- entities:createSilentNPC()
- Creates a non-interactive NPC.
- returns: New SilentNPC instance.
- entities:setPath(entity, table, loop)
- DEPRECATED: path can now be set by directly calling the NPC's setPathmethod
- Helper method for setting an NPC's path.
- entity: (RPEntity) Then entity whose path is being set.
- table: (LuaTable) Table with list of coordinates representing nodes.
- loop: (boolean) Iftrue, the entity's path should loop.
- entities:setPathAndPosition(entity, table, loop) <nowiki>
- DEPRECATED: path can now be set by directly calling the NPC's setPathmethod
- Helper function for setting an NPC's path & starting position.
- entity: (RPEntity) Then entity whose path is being set.
- table: (LuaTable) Table with list of coordinates representing nodes.
- loop: (boolean) Iftrue, the entity's path should loop.
- entities:createSign(visible)
- Creates a new Template:StendhalFile entity.
- visible: (boolean) (optional) Iffalse, the sign will not have a visual representation.
- returns: New Signinstance.
- entities:createShopSign(name, title, caption, seller)
- Creates a new Template:StendhalFile entity.
- name: (String) The shop name.
- title: (String) The sign title.
- caption: (String) The caption above the table.
- seller: (boolean)true, if this sign is for items sold by an NPC (defaults totrueifnull).
- returns: New ShopSigninstance.
- entities:summonCreature(table)
- Summons a creature into the area.
- table: Key-value table containing parameters for summoning creature.
- keys:
- name: (string) Name of creature to be summoned.
- zone: (string) Name of zone where creature should be summoned.
- x: (int) Horizontal position of summon location.
- y: (int) Vertical position of summon location.
- summoner: (string) (optional) Name of entity doing the summoning (used for logging game events).
- raid: (bool) (optional) Whether or not the creature should be aRaidCreatureinstance (default: true).
 
Lua Entity Classes[编辑]
LuaSpeakerNPC[编辑]
- Inherits: SpeakerNPC
Public methods:
- add (states, triggers, conditions, nextState, reply, actions)
- Additional method to support passing Lua data types as parameters. Template:MethodParam
Template:MethodParam Template:MethodParam Template:MethodParam Template:MethodParam Template:MethodParam
- setPath (table, loop)
- Set a path for this entity to follow. Template:MethodParam
- setPathAndPosition (table, loop)
- Set path & starting position for entity. The starting position is the first node in the path. Template:MethodParam
LuaSilentNPC[编辑]
- Inherits: SilentNPC
Public methods:
- setPath (table, loop)
- Set a path for this entity to follow. Template:MethodParam
- setPathAndPosition (table, loop)
- Set path & starting position for entity. The starting position is the first node in the path. Template:MethodParam
entities.manager[编辑]
This is simply the Template:StendhalFile instance.
Public methods:
TODO
quests[编辑]
Adds helper functions for creating & manipulating quests & exposes select public methods of the Template:StendhalFile class.
Methods:
- quests:create(slotName, name)
- Creates a new quest.
- slotName: (optional) The string identifier for the quest.
- name: (optional) The human-readable name that can be shown in travel log.
- returns: New Template:StendhalFile instance.
- quests:load(quest)
- Adds a quest to the world.
- quest: The Template:StendhalFile instance to be loaded.
- quests:unload(questName)
- Removes a quest from the world.
- questName: String name of the quest to be removed.
- quests:cache(quest)
- Caches a quest for loading at server startup.
- quest: Template:StendhalFile instance to be loaded.
- aliases:
- quests:register
 
- quests:isLoaded(quest)
- Checks if a quest has been loaded.
- quest: Template:StendhalFile instance to check.
- returns: trueif the instance matches stored quests.
- quests:listAll(player)
- List all quests the player knows about.
- player: Player to create the report for.
- returns: String report.
- quests:list(player, questName)
- Creates a report on a specified quest for a player.
- player: Player to create the report for.
- questName: Name of quest to be reported.
- returns: String report.
- quests:listStates(player)
- Dumps the internal quest states for the specified player. This is used for the Template:StendhalFile.
- player: Player to create the report for.
- returns: String report.
- quests:getQuest(questName)
- Retrieves the Template:StendhalFile object for a named quest.
- questName: Name of quest.
- returns: IQuestornullif doesn't exist.
- quests:getQuestFromSlot(questSlot)
- Retrieves the Template:StendhalFile object for a quest.
- questSlot: Quest identifier string.
- returns: IQuestornullif doesn't exist.
- quests:getOpen(player)
- Retrieves a list of open quests from a player.
- player: Template:StendhalFile instance to be checked.
- returns: List of string identifiers for open quests.
- quests:getCompleted(player)
- Retrieves a list of completed quests from a player.
- player: Template:StendhalFile instance to be checked.
- returns: List of string identifiers for completed quests.
- quests:getIncomplete(player, region)
- Retrieves a list of incomplete quests in a specified region.
- player: Template:StendhalFile instance to be checked.
- region: Region name/identifier.
- returns: List of string identifiers of incomplete quests in region.
- quests:getRepeatable(player)
- Retrieves a list of quests a player has completed, and can now do again.
- player: Template:StendhalFile instance to be checked.
- returns:
- quests:getDescription(player, questName)
- Retrieves the description of a quest.
- player: Template:StendhalFile instance to be checked.
- questName: Name of the quest.
- returns: Stringdescription.
- quests:getLevelWarning(player, questName)
- If the quest is too dangerous, add a warning unless the player has already completed it.
- player: Template:StendhalFile instance to be checked.
- questName: Name of the quest.
- returns: String
- quests:getProgressDetails(player, questeName)
- Retrieves details on the progress of the quest.
- player: Template:StendhalFile instance to be checked.
- questName: Name of the quest.
- returns: List<String>
- quests:getNPCNamesForUnstartedInRegionForLevel(player, region)
- Retrieves a list of the unique npc names for unstarted quests in a specified region.
- player: Template:StendhalFile instance to be checked.
- region: Region to check in.
- returns: List<String>
- quests:getDescriptionForUnstartedInRegionFromNPCName(player, region, name)
- Retrieves quest descriptions for unstarted quests in a specified region matching a specific NPC name.
- player: Template:StendhalFile instance to be checked.
- region: Region to check in.
- name: Name of NPC.
- returns: List<String>
quests.simple[编辑]
A special class for creating a simple collect single item quest.
Methods:
- quests.simple:create(slotName, properName, npcName)
- slotName: Stringidentifier to be used for quest.
- properName: Human-readable name to be displayed in travel log.
- npcName: The NPC associated with the quest.
- returns: Template:StendhalFile instance.
SimpleQuest Object[编辑]
Methods:
- setDescription(descr)
- descr: (String)
- setRepeatable(delay)
- delay: (Integer)
- setItemToCollect(itemName, quantity)
- itemName: (String)
- quantity: (int)
- setXPReward(xp)
- xp: (int)
- setKarmaReward(karma)
- karma: (double)
- setKarmaAcceptReward(karma)
- karma: (double)
- setKarmaRejectReward(karma)
- karma: (double)
- addItemReward(itemName, quantity)
- itemName: (String)
- quantity: (int) (optional)
- addStatReward(id, amount)
- id: (String) See IDs below.
- amount: (int)- IDs:
- xp:
- def:
- atk:
- ratk:
 
- setVerboseReward(verbose)
- verbose: (boolean)
- setReply(id, reply)
- id: (String) See IDs below.
- reply: (String)- IDs:
- request:
- accept:
- reject:
- reward:
- verbose_reward_prefix:
- already_active:
- missing:
- no_repeat:
- cooldown_prefix:
 
- setRegion(regionName)
- regionName: (String)
Also inherits methods from Template:StendhalFile:
Example:
-- create SimpleQuest instance
local quest = simpleQuest:create("wood_for_lua", "Wood for Lua", "Lua")
quest:setDescription("Lua needs help gathering wood.")
quest:setRequestReply("I need help gathering some wood. Will you help me?")
quest:setAcceptReply("Great!")
quest:setRewardReply("Thank a bunch!")
quest:setRejectReply("Fine! I don't need your help anyway.")
quest:setItemToCollect("wood", 5)
quest:setRepeatable(true)
quest:setRepeatDelay(10)
quest:setXPReward(50)
quest:setKarmaReward(5.0)
quest:addItemReward("rose", 3)
quest:addItemReward("money", 100)
quest:setRegion(Region.SEMOS_CITY)
quests:register(quest)
conditions[编辑]
Object for creating Template:StendhalFile instances.
Methods:
- conditions:create(function)
- Creates a custom Template:StendhalFile.
- function: Lua function to be invoked when ChatCondition.fireis called.
- returns: New ChatConditioninstance.
- conditions:notCondition(condition)
- Creates a Template:StendhalFile.
- condition: Can be a ChatCondition,LuaValuecontaining aChatConditioninstance, a Lua table ofChatConditioninstances, or a function.
- returns: New NotConditioninstance.
- conditions:andCondition(conditionList)
- Creates an Template:StendhalFile.
- conditionList: Lua table containing ChatConditioninstances.
- returns: New AndConditioninstance.
actions[编辑]
Object for creating Template:StendhalFile instances.
Methods:
- actions:create(function)
- Creates a custom Template:StendhalFile.
- function: A Lua function to be executed when ChatAction.fireis called.
- returns: New ChatActioninstance.
- actions:multiple(actionList)
- Helper method for creating a Template:StendhalFile instance.
- actionList: A Lua table containing ChatAction instances.
- returns: New MultipleActionsinstance.
merchants[编辑]
Exposes merchant handling classes & functions to Lua.
Members:
- merchants.shops
- This is the Template:StendhalFile instance.
- public methods: TODO
Methods:
- merchants:add(merchantType, npc, prices, addOffer)
- Adds merchant behavior to a Template:StendhalFile.
- merchantType: If set to "buyer", will add buyer behavior, otherwise will be "seller".
- npc: The SpeakerNPC to add the behavior to.
- prices: List of items & their prices (can be instance of either Map<String, Integer> or a Lua table).
- addOffer: If true, will add default replies for "offer" (default:true).
- merchants:addSeller(npc, prices, addOffer)
- Adds seller behavior to a Template:StendhalFile.
- npc: The SpeakerNPC to add the behavior to.
- prices: List of items & their prices (can be instance of either Map<String, Integer> or a Lua table).
- addOffer: If true, will add default replies for "offer" (default:true).
- merchants:addBuyer(npc, prices, addOffer)
- Adds buyer behavior to a Template:StendhalFile.
- npc: The SpeakerNPC to add the behavior to.
- prices: List of items & their prices (can be instance of either Map<String, Integer> or a Lua table).
- addOffer: If true, will add default replies for "offer" (default:true).
arrays[编辑]
Handles some conversion of Java arrays & lists to Lua tables.
Methods:
- arrays:toTable(list)
- Converts a Java array or list to a Lua table.
- list: Java array or list.
- returns: New Lua table with contents of listadded.
grammar[编辑]
Exposes the Template:StendhalFile parser instance to Lua.
Static Classes & Enumerations[编辑]
ConversationStates[编辑]
The Template:StendhalFile enum.
Example usage:
local npc = entities:createSpeakerNPC("foo")
npc:setCurrentState(ConversationStates.IDLE)
ConversationPhrases[编辑]
The Template:StendhalFile class.
Example usage:
local npc = entities:createSpeakerNPC("foo")
npc:add(ConversationStates.IDLE,
	ConversationPhrases.GREETING_MESSAGES,
	nil,
	ConversationStates.ATTENDING,
	"Hello! How can I help you.",
	nil)
CollisionAction[编辑]
The Template:StendhalFile enum.
Example usage:
local npc = entities:createSilentNPC() npc:setCollisionAction(CollisionAction.STOP)
SkinColor[编辑]
The Template:StendhalFile enum.
Example usage:
local npc = entities:createSpeakerNPC("foo")
npc:setOutfit("body=0,head=0,hair=3,dress=5")
npc:setOutfitColor("skin", SkinColor.DARK)
Direction[编辑]
The Template:StendhalFile enum.
Example usage:
local npc = entities:createSpeakerNPC("foo")
npc:setDirection(Direction.DOWN)
DaylightPhase[编辑]
The Template:StendhalFile enum.
Region[编辑]
The Template:StendhalFile class.
MathHelper[编辑]
The Template:StendhalFile class.
Color[编辑]
The java.awt.Color class.
Example usage:
local npc = entities:createSpeakerNPC("foo")
npc:setOutfit("body=0,head=0,hair=3,dress=5")
npc:setOutfitColor("dress", Color.BLUE)
Supplemental Methods[编辑]
A few convenience methods are added to make scripting easier.
String Manipulation[编辑]
The following methods have been added to the built-in Lua string library.
- string.startsWith(st, prefix)
- Checks if a string begins with a set of characters.
- st: The string to be checked.
- prefix: The prefix to be compared with.
- returns: trueifprefixmatches the beginning characters ofst.- aliases:
- string.beginsWith
 
- string.endsWith(st, suffix)
- Checks if a string ends with a set of characters.
- st: The string to be checked.
- suffix: The suffix to be compared with.
- returns: trueifsuffixmatches then end characters ofst.
- string.isNumber(st)
- Checks if a string contains numeric characters only.
- st: The string to be checked.
- returns: trueif all characters are numeric,falseotherwise.- aliases:
- string.isNumeric
 
- string.trim(st)
- Removes leading & trailing whitespace from a string.
- st: The string to be trimmed.
- returns: Trimmed string.
- string.ltrim(st)
- Removes leading whitespace from a string.
- st: The string to be trimmed.
- returns: Trimmed string.
- string.rtrim(st)
- Removes trailing whitespace from a string.
- st: The string to be trimmed.
- returns: Trimmed string.
- string.builder(st)
- Creates a new instance of java.lang.StringBuilder.
- st: (optional) String to append on instantiation.
- returns: new StringBuilder instance.
Table Manipulation[编辑]
The following methods have been added to the built-in Lua table library.
- table.concat(tbl1, tbl2)
- Merges the contents of one table into another.
- tbl1: The table receiving the new content.
- tbl2: The table containing the content to be copied.
- table.contains (table, o)
- Checks if a table contains a value. Template:MethodParam
- returns: (boolean)trueifois intable.
- table.clean(tbl)
- Removes nilvalues from a table.
- tbl: The table to be cleaned.
- returns: Copy of tblwithnilvalues removed.
- table.join (table, delim)
- Joins a table of strings into a string. Template:MethodParam
- returns: (string) The resulting string.
























