Lua Scripting Guide

Discussion in 'Programming & Scripting' started by Evil Hero, Mar 23, 2010.

  1. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    Welcome to my Scripting Guide!

    I hope you'll enjoy your stay and learn much from it :D

    This guide is completly about lua related scripting, you'll learn here everything from basics up to advanced stuff.
    If you think there's something missing then tell me what and it'll be added.

    Please don't leave without commenting!! thanks :rolleyes:

    This Thread is based on my old Tutorial

    Thread History

    I suggest that you go step by step, so nothing will stay unknown to you.
     
    Last edited: Dec 6, 2010
  2. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART I - Functions...(What are they? What are they for?)

    Functions are basicly just the thing which tells the server what you want to be happen with this Script.
    There are many functions but you have to Split them into 2 Groups.

    Group 1: The "Primary Functions" those functions are always listened at the very first start of a Script they tell what kind of action will be executed now.
    Group 2: The "Secondary Functions" those functions are always ordered under the "Primary Function" but they are as important as the "Primary Functions".

    Now we go into Details...

    Let's start with the Primary Function.

    Like I already stated those are the Functions which have to be ontop always. Let us go deeper into details so you'll understand why it is like that!

    List of the "Primary Functions" NOTE (The Functions maybe variate depending on which server distro you use!)

    Basic Ones:

    Code (Lua):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2. function onStepIn(cid, item, frompos, itemEx, topos)
    3. function onStepOut(cid, item, frompos, itemEx, topos)
    4. function onSay(cid, words, param)
    5. function onEquip(cid, item, slot)
    6. function onDeEquip(cid, item, slot)
    7. function onAddItem(cid, moveitem, tileitem, position)
    8. function onRemoveItem(cid, moveitem, tileitem, position)
    Creaturescripts:

    Code (Lua):
    1. function onLogin(cid)
    2. function onLogout(cid)
    3. function onJoinChannel(cid, channel, users)
    4. function onLeaveChannel(cid, channel, users)
    5. function onAdvance(cid, skill, oldLevel, newLevel)
    6. function onLook(cid, thing, position, lookDistance)
    7. function onSendMail((cid, receiver, open, itemBox)
    8. function onReceiveMail(cid, sender, open, itemBox)
    9. function onTradeRequest(cid, target, item)
    10. function onTradeAccept(cid, target, item)
    11. function onTextEdit(cid, item, newText)
    12. function onReportBug(cid, comment)
    13. function onThink(cid, interval)
    14. function onDirection(cid, old, current)
    15. function onOutfit(cid, old, current)
    16. function onStatsChange(cid, attacker, type, combat, value)
    17. function onAreaCombat(cid, ground, position, aggressive)
    18. function onPush(cid, target)
    19. function onTarget(cid, target)
    20. function onFollow(cid, target)
    21. function onCombat(cid, target)
    22. function onAttack(cid, target)
    23. function onCast(cid, target)
    24. function onKill(cid, target, damage, flags)
    25. function onDeath(cid, corpse, deathList)
    26. function onPreprareDeath(cid, deathList)
    27.  
    Globalevents:

    Code (Lua):
    1. function onStartUp()
    2. function onShutdown()
    3. function onGlobalSave()
    4. function onRecord(current, old, cid)
    5. function onTime(time)
    6. function onThink(interval)
    Those are the Functions which the Updated Distros have so far.

    Let me explain you each function now...

    Code (Lua):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    Like you can easy guess this will make something happen when you use something

    example:

    You pull a lever and a wall will be created.


    Code (Lua):
    1. function onStepIn(cid, item, frompos, itemEx, topos)
    This will make something happen when you walk on a specificated tile, yes you heard right this one will ONLY be executed when you walk on a tile.

    example:

    You walk on a tile and get an welcome message.


    Code (Lua):
    1. function onStepOut(cid, item, frompos, itemEx, topos)
    This one is just the difference from "onStepIn" this one ONLY works when you step from a specificated tile.

    example:

    You walk from a tile and will be teleported to another position.


    Code (Lua):
    1. function onSay(cid, words, param)
    This one will only work when a player says a specificated word which will execute the script then...

    example:

    The Player has to say "!Quest" to start an quest.


    Code (Lua):
    1. function onEquip(cid, item, slot)
    To get this in order to work you have to put an item into one of your equipment slots.

    example:

    You put an Crown armor into your Body Equipment Slot.


    Code (Lua):
    1. function onDeEquip(cid, item, slot)
    Almost same as "onEquip" but in order to get it work you have to put off an item from your Equipment Slot.

    example:

    You put the Crown armor off from your Body Equipment Slot.


    Code (Lua):
    1. function onAddItem(cid, moveitem, tileitem, position)
    This is one of the less used Functions but it's really usefull sometimes, you have to put an item on a specificated tile in order to get it to work.

    example:

    You put an Axe on a sacrfice table, the item will be gone and another item will be created.

    Code (Lua):
    1. function onRemoveItem(cid, moveitem, tileitem, position)
    This function is also not much used. You need to remove an item from a specificated tile in order to get it to work

    example:

    You pickup a a key from ground and a door will open.

    Going to edit the post later to add the rest.

    This was a little explanation of the "Primary Functions"
    You should now be able to recognise what usage which function has.

    "Secondary" List: -- Functions from tfs 0.3.6pl1
    Code (Lua):
    1. //get*
    2.     getCreatureHealth(cid)
    3.     getCreatureMaxHealth(cid)
    4.     getCreatureHideHealth(cid)
    5.     getCreatureMana(cid)
    6.     getCreatureMaxMana(cid)
    7.     getCreatureSpeakType(cid)
    8.     getCreatureMaster(cid)
    9.     getCreatureSummons(cid)
    10.     getCreatureOutfit(cid)
    11.     getCreaturePosition(cid)
    12.     getCreatureLookDirection(cid)
    13.     getCreatureName(cid)
    14.     getCreatureSpeed(cid) //TODO
    15.     getCreatureBaseSpeed(cid) //TODO
    16.     getCreatureTarget(cid) //TODO
    17.     getCreatureByName(name)
    18.     getCreatureSkullType(cid)
    19.     getCreatureCondition(cid, condition[, subId]) //TODO
    20.     getCreatureNoMove(cid) //TODO
    21.     getMonsterInfo(name)
    22.     getMonsterHealingSpells(name) //TODO
    23.     getMonsterAttackSpells(name) //TODO
    24.     getMonsterLootList(name) //TODO
    25.     getMonsterSummonList(name) //TODO
    26.     getMonsterTargetList(cid) //TODO
    27.     getMonsterFriendList(cid) //TODO
    28.     getPlayerByNameWildcard(name~[, ret = false]) //TODO
    29.     getPlayerLossSkill(cid) //TODO
    30.     getPlayerLossPercent(cid, lossType) //TODO
    31.     getPlayerGUIDByName(name[, multiworld = false]) //TODO
    32.     getPlayerNameByGUID(guid[, multiworld = false[, displayError = true]]) //TODO
    33.     getPlayerFood(cid)
    34.     getPlayerLevel(cid)
    35.     getPlayerExperience(cid)
    36.     getPlayerMagLevel(cid[, ignoreBuffs = false]) //TODO
    37.     getPlayerSpentMana(cid) //TODO
    38.     getPlayerAccess(cid)
    39.     getPlayerGhostAccess(cid)
    40.     getPlayerSkillLevel(cid, skillId)
    41.     getPlayerSkillTries(cid, skillId) //TODO
    42.     getPlayerTown(cid)
    43.     getPlayerVocation(cid)
    44.     getPlayerRequiredMana(cid, magicLevel) //TODO
    45.     getPlayerRequiredSkillTries(cid, skillId, skillLevel) //TODO
    46.     getPlayerItemCount(cid, itemid[, subType = -1])
    47.     getPlayerSoul(cid)
    48.     getPlayerAccountId(cid) //TODO
    49.     getPlayerAccount(cid) //TODO
    50.     getPlayerIp(cid) //TODO
    51.     getPlayerFreeCap(cid)
    52.     getPlayerLight(cid)
    53.     getPlayerSlotItem(cid, slot)
    54.     getPlayerWeapon(cid[, ignoreAmmo = false]) //TODO
    55.     getPlayerItemById(cid, deepSearch, itemId[, subType = -1]) //TODO
    56.     getPlayerDepotItems(cid, depotid)
    57.     getPlayerGuildId(cid)
    58.     getPlayerGuildName(cid)
    59.     getPlayerGuildRank(cid)
    60.     getPlayerGuildNick(cid)
    61.     getPlayerGuildLevel(cid) //TODO: From here, all bottoms
    62.     getPlayerSex(cid)
    63.     getPlayerStorageValue(uid, key)
    64.     getPlayerGUID(cid)
    65.     getPlayerFlagValue(cid, flag)
    66.     getPlayerCustomFlagValue(cid, flag)
    67.     getPlayerPromotionLevel(cid)
    68.     getPlayerGroupId(cid)
    69.     getPlayerLearnedInstantSpell(cid, name)
    70.     getPlayerInstantSpellCount(cid)
    71.     getPlayerInstantSpellInfo(cid, index)
    72.     getPlayerBlessing(cid, blessing)
    73.     getPlayerStamina(cid)
    74.     getPlayerExtraExpRate(cid)
    75.     getPlayerPartner(cid)
    76.     getPlayerParty(cid)
    77.     getPlayerPremiumDays(cid)
    78.     getPlayerBalance(cid)
    79.     getPlayerMoney(cid)
    80.     getPlayerSkullTicks(cid, type)
    81.     getPlayerRates(cid)
    82.     getPlayerLastLogin(cid)
    83.     getPlayerLastLoginSaved(cid)
    84.     getPlayerAccountManager(cid)
    85.     getInstantSpellInfo(cid, name)
    86.     getPlayersByAccountId(accountNumber)
    87.     getPlayersByIp(ip[, mask = 0xFFFFFFFF])
    88.     getChannelUsers(channelId)
    89.     getPlayersOnline()
    90.     getPartyMembers(lid)
    91.     getAccountIdByName(name)
    92.     getAccountByName(name)
    93.     getAccountIdByAccount(accName)
    94.     getAccountByAccountId(accId)
    95.     getIpByName(name)
    96.     getItemRWInfo(uid)
    97.     getItemProtection(uid)
    98.     getItemDescriptionsById(itemid)
    99.     getItemWeightById(itemid, count[, precise])
    100.     getItemDescriptions(uid)
    101.     getItemWeight(uid[, precise])
    102.     getItemAttack(uid)
    103.     getItemExtraAttack(uid)
    104.     getItemDefense(uid)
    105.     getItemExtraDefense(uid)
    106.     getItemArmor(uid)
    107.     getItemAttackSpeed(uid)
    108.     getItemHitChance(uid)
    109.     getItemShootRange(uid)
    110.     getItemIdByName(name[, displayError = true])
    111.     getItemLevelDoor(itemid)
    112.     getItemWeaponType(uid)
    113.     getFluidSourceType(type)
    114.     getContainerSize(uid)
    115.     getContainerCap(uid)
    116.     getContainerCapById(itemid)
    117.     getContainerItem(uid, slot)
    118.     getDepotId(uid)
    119.     getTileItemById(pos, itemId[, subType = -1])
    120.     getTileItemByType(pos, type)
    121.     getTileThingByPos(pos)
    122.     getTileInfo(pos)
    123.     getTopCreature(pos)
    124.     getClosestFreeTile(cid, targetpos[, extended = false[, ignoreHouse = true]])
    125.     getThingFromPos(pos)
    126.     getThing(uid)
    127.     getThingPos(uid)
    128.     getHouseInfo(id)
    129.     getHouseAccessList(houseid, listid)
    130.     getHouseByPlayerGUID(playerGUID)
    131.     getHouseFromPos(pos)
    132.     getTownId(townName)
    133.     getTownName(townId)
    134.     getTownTemplePosition(townId)
    135.     getTownHouses(townId)
    136.     getWorldType()
    137.     getWorldTime()
    138.     getWorldLight()
    139.     getWorldCreatures(type) //0 players, 1 monsters, 2 npcs, 3 all
    140.     getWorldUpTime()
    141.     getHighscoreString(skillId)
    142.     getVocationInfo(id)
    143.     getGuildId(guildName)
    144.     getGuildMotd(guildId)
    145.     getSpectators(centerPos, rangex, rangey[, multifloor = false])
    146.     getSearchString(fromPosition, toPosition[, fromIsCreature = false[, toIsCreature = false]])
    147.     getWaypointPosition(name)
    148.     getGameState()
    149.     getNotationsCount(accId)
    150.     getBanData(value)
    151.     getBanList(type[, value])
    152.     getBanReason(id)
    153.     getBanAction(id[, ipBanishment])
    154.     getGlobalStorageValue(valueid)
    155.     getExperienceStage(level)
    156.     getConfigFile()
    157.     getConfigValue(key)
    158.     getModList()
    159.     loadmodlib(libName)
    160.     domodlib(libName)
    161.     getLogsDir()
    162.     getDataDir()
    163.     getWaypointList()
    164.     getTalkActionList()
    165.     getExperienceStageList()
    166.  
    167.     //set*
    168.     setCreatureMaxHealth(cid, health)
    169.     setCreatureMaxMana(cid, mana)
    170.     setHouseOwner(houseid, ownerGUID)
    171.     setHouseAccessList(houseid, listid, listtext)
    172.     setItemName(uid)
    173.     setItemPluralName(uid)
    174.     setItemArticle(uid)
    175.     setItemAttack(uid, attack)
    176.     setItemExtraAttack(uid, extraattack)
    177.     setItemDefense(uid, defense)
    178.     setItemArmor(uid, armor)
    179.     setItemExtraDefense(uid, extradefense)
    180.     setItemAttackSpeed(uid, attackspeed)
    181.     setItemHitChance(uid, hitChance)
    182.     setItemShootRange(uid, shootRange)
    183.     setCombatArea(combat, area)
    184.     setCombatCondition(combat, condition)
    185.     setCombatParam(combat, key, value)
    186.     setConditionParam(condition, key, value)
    187.     setCombatCallBack(combat, key, function_name)
    188.     setCombatFormula(combat, type, mina, minb, maxa, maxb)
    189.     setConditionFormula(combat, mina, minb, maxa, maxb)
    190.     setGlobalStorageValue(key, newValue)
    191.     setWorldType(type)
    192.  
    193.     //do*
    194.     doCreatureAddHealth(cid, health[, force])
    195.     doCreatureAddMana(cid, mana)
    196.     doCreatureSetDropLoot(cid, doDrop)
    197.     doCreatureSetSkullType(cid, skull)
    198.     doCreatureSetSpeakType
    199.     doCreatureSetLookDirection(cid, dir)
    200.     doPlayerSetMaxCapacity(cid, cap)
    201.     doCreatureChangeOutfit(cid, outfit)
    202.     doCreatureSay(uid, text, type[, ghost = false[, cid = 0[, pos]]])
    203.     doCreatureSetNoMove(cid, cannotMove)
    204.     doSetCreatureLight(cid, lightLevel, lightColor, time)
    205.     doSetCreatureOutfit(cid, outfit, time)
    206.     doRemoveCreature(cid[, executeLogout = true])
    207.     doMoveCreature(cid, direction)
    208.     doConvinceCreature(cid, target)
    209.     doChallengeCreature(cid, target)
    210.     doChangeSpeed(cid, delta)
    211.     doSummonMonster(name, pos)
    212.     doCreateMonster(name, pos)
    213.     doMonsterChangeTarget(cid)
    214.     doMonsterSetTarget(cid, target)
    215.     doCreateNpc(name, pos)
    216.     doSetMonsterOutfit(cid, name, time)
    217.     doPlayerBroadcastMessage(cid, message[, type])
    218.     doPlayerSetSex(cid, newSex)
    219.     doPlayerSetTown(cid, townid)
    220.     doPlayerSetVocation(cid, voc)
    221.     doPlayerSetStorageValue(uid, key, newValue)
    222.     doPlayerSetGroupId(cid, newGroupId)
    223.     doPlayerSetPromotionLevel(cid, level)
    224.     doPlayerSetStamina(cid, minutes)
    225.     doPlayerSetBalance(cid, balance)
    226.     doPlayerSetExtraExpRate(cid, value)
    227.     doPlayerSetPartner(cid, guid)
    228.     doPlayerRemoveItem(cid, itemid, count[, subtype])
    229.     doPlayerAddExperience(cid, amount)
    230.     doPlayerSetGuildId(cid, id)
    231.     doPlayerSetGuildRank(cid, rank)
    232.     doPlayerSetGuildNick(cid, nick)
    233.     doPlayerAddOutfit(cid,looktype, addons)
    234.     doPlayerRemoveOutfit(cid,looktype, addons)
    235.     doPlayerSetRedSkullTicks(cid, amount)
    236.     doPlayerSetLossPercent(cid, lossType, newPercent)
    237.     doPlayerSetLossSkill(cid, doLose)
    238.     doPlayerAddSkillTry(cid, skillid, n)
    239.     doPlayerAddSpentMana(cid, amount)
    240.     doPlayerAddSoul(cid, soul)
    241.     doPlayerAddItem(uid, itemid[, count/subtype[, canDropOnMap = true]])
    242.     doPlayerAddItemEx(cid, uid[, canDropOnMap = false])
    243.     doPlayerSendTextMessage(cid, MessageClasses, message)
    244.     doPlayerSendChannelMessage(cid, author, message, SpeakClasses, channel)
    245.     doPlayerSendToChannel(cid, targetId, SpeakClasses, message, channel[, time])
    246.     doPlayerAddMoney(cid, money)
    247.     doPlayerRemoveMoney(cid, money)
    248.     doPlayerTransferMoneyTo(cid, target, money)
    249.     doPlayerPopupFYI(cid, message)
    250.     doPlayerSendTutorial(cid, id)
    251.     doPlayerAddMapMark(cid, pos, type[, description])
    252.     doPlayerAddPremiumDays(cid, days)
    253.     doPlayerAddBlessing(cid, blessing)
    254.     doPlayerAddStamina(cid, minutes)
    255.     doPlayerResetIdleTime(cid)
    256.     doPlayerLearnInstantSpell(cid, name)
    257.     doPlayerUnlearnInstantSpell(cid, name)
    258.     doPlayerFeed(cid, food)
    259.     doPlayerSendCancel(cid, text)
    260.     doPlayerSendDefaultCancel(cid, ReturnValue)
    261.     doPlayerSetRate(cid, type, value)
    262.     doPlayerJoinParty(cid, lid)
    263.     doPlayerSendOutfitWindow(cid)
    264.     doPlayerSave(cid[, shallow = false])
    265.     doCreateItem(itemid, type/count, pos)
    266.     doCreateItemEx(itemid[, count/subtype])
    267.     doAddContainerItemEx(uid, virtuid)
    268.     doAddContainerItem(uid, itemid[, count/subtype])
    269.     doChangeTypeItem(uid, newtype)
    270.     doDecayItem(uid)
    271.     doRemoveItem(uid[, count])
    272.     doTransformItem(uid, toitemid[, count/subtype])
    273.     doSetItemActionId(uid, actionid)
    274.     doSetItemText(uid, text[, writer[, date]])
    275.     doSetItemSpecialDescription(uid, desc)
    276.     doSetItemOutfit(cid, item, time)
    277.     doSetItemProtection(uid, value)
    278.     doTileAddItemEx(pos, uid)
    279.     doTileQueryAdd(uid, pos[, flags])
    280.     doAddCondition(cid, condition)
    281.     doRemoveCondition(cid, type[, subId])
    282.     doRemoveConditions(cid[, onlyPersistent])
    283.     doAreaCombatHealth(cid, type, pos, area, min, max, effect)
    284.     doTargetCombatHealth(cid, target, type, min, max, effect)
    285.     doAreaCombatMana(cid, pos, area, min, max, effect)
    286.     doTargetCombatMana(cid, target, min, max, effect)
    287.     doAreaCombatCondition(cid, pos, area, condition, effect)
    288.     doTargetCombatCondition(cid, target, condition, effect)
    289.     doAreaCombatDispel(cid, pos, area, type, effect)
    290.     doTargetCombatDispel(cid, target, type, effect)
    291.     doCombat(cid, combat, param)
    292.     doTeleportThing(cid, newpos[, pushmove = true])
    293.     doCreateTeleport(itemid, topos, createpos)
    294.     doSendMagicEffect(pos, type[, player])
    295.     doSendDistanceShoot(frompos, topos, type[, player])
    296.     doSendAnimatedText(pos, text, color[, player])
    297.     doShowTextDialog(cid, itemid, text)
    298.     doRelocate(pos, toPos[, creatures = true])
    299.     doBroadcastMessage(message, type)
    300.     doWaypointAddTemporial(name, pos)
    301.     doSetGameState(stateId)
    302.     doAddIpBanishment(ip[, length[, comment[, admin]]])
    303.     doAddNamelock(name[, reason[, action[, comment[, admin]]]])
    304.     doAddBanishment(accId[, length[, reason[, action[, comment[, admin]]]]])
    305.     doAddDeletion(accId[, reason[, action[, comment[, admin]]]]])
    306.     doAddNotation(accId[, reason[, action[, comment[, admin]]]]])
    307.     doRemoveIpBanishment(ip[, mask])
    308.     doRemoveNamelock(name)
    309.     doRemoveBanisment(accId)
    310.     doRemoveDeletion(accId)
    311.     doRemoveNotations(accId)
    312.     doSaveServer()
    313.     doReloadInfo(id[, cid])
    314.     doCleanHouse(houseId)
    315.     doCleanMap()
    316.     doRefreshMap()
    317.  
    318.     //is*
    319.     isCreature(cid)
    320.     isMonster(uid)
    321.     isNpc(uid)
    322.     isPlayer(cid)
    323.     isPlayerPzLocked(cid)
    324.     isItemStackable(itemid)
    325.     isItemRune(itemid)
    326.     isItemMovable(itemid)
    327.     isItemDoor(itemid)
    328.     isItemContainer(itemid)
    329.     isItemFluidContainer(itemid)
    330.     isContainer(uid)
    331.     isCorpse(uid)
    332.     isMovable(uid)
    333.     isSightClear(fromPos, toPos, floorCheck)
    334.     isIpBanished(ip[, mask])
    335.     isPlayerNamelocked(name)
    336.     isAccountBanished(accId)
    337.     isAccountDeleted(accId)
    338.     isInArray({array}, value[, lower = true])
    339.  
    340.     //others
    341.     registerCreatureEvent(uid, eventName)
    342.     createCombatArea({area}[, {exArea}])
    343.     createConditionObject(type[, ticks[, buff[, subId]]])
    344.     addDamageCondition(condition, rounds, time, value)
    345.     addOutfitCondition(condition, lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet)
    346.     createCombatObject()
    347.     numberToVariant(number)
    348.     stringToVariant(string)
    349.     positionToVariant(pos)
    350.     targetPositionToVariant(pos)
    351.     variantToNumber(var)
    352.     variantToString(var)
    353.     variantToPosition(var)
    354.     canPlayerWearOutfit(cid, lookType, addons)
    355.     executeRaid(name)
    356.     addEvent(callback, delay, ...)
    357.     stopEvent(eventid)
    358.     hasProperty(uid)
    359.  
    360.     md5(str)
    361.     sha1(str)
    362.  
    363.     //db table
    364.     db.executeQuery(query)
    365.     db.storeQuery(query)
    366.     db.escapeString(str)
    367.     db.escapeBlob(s, length)
    368.     db.stringComparisonOperator()
    369.     db.lastInsertId()
    370.  
    371.     //result table
    372.     result.getDataInt(resId, s)
    373.     result.getDataLong(resId, s)
    374.     result.getDataString(resId, s)
    375.     result.getDataStream(resId, s, length)
    376.     result.next(resId)
    377.     result.free(resId)
    378.  
    379.     //bit table
    380.     #bit.cast
    381.     bit.bnot(n)
    382.     bit.band(type, n)
    383.     bit.bor(type, n)
    384.     bit.bxor(type, n)
    385.     bit.lshift(type, n)
    386.     bit.rshift(type, n)
    387.     #bit.arshift
    388.     #bit.ucast
    389.     bit.ubnot(n)
    390.     bit.uband(type, n)
    391.     bit.ubor(type, n)
    392.     bit.ubxor(type, n)
    393.     bit.ulshift(type, n)
    394.     bit.urshift(type, n)
    395.     #bit.uarshift
    396.  
    397.     //compats
    398.     table.getPos = table.find
    399.     doSetCreatureDropLoot = doCreatureSetDropLoot
    400.     doPlayerSay = doCreatureSay
    401.     doPlayerAddMana = doCreatureAddMana
    402.     playerLearnInstantSpell = doPlayerLearnInstantSpell
    403.     doPlayerRemOutfit = doPlayerRemoveOutfit
    404.     pay = doPlayerRemoveMoney
    405.     broadcastMessage = doBroadcastMessage
    406.     getPlayerName = getCreatureName
    407.     getPlayerPosition = getCreaturePosition
    408.     getCreaturePos = getCreaturePosition
    409.     creatureGetPosition = getCreaturePosition
    410.     getPlayerMana = getCreatureMana
    411.     getPlayerMaxMana = getCreatureMaxMana
    412.     hasCondition = getCreatureCondition
    413.     isMoveable = isMovable
    414.     isItemMoveable = isItemMovable
    415.     saveData = saveServer
    416.     savePlayers = saveServer
    417.     getPlayerSkill = getPlayerSkillLevel
    418.     getPlayerSkullType = getCreatureSkullType
    419.     getCreatureSkull = getCreatureSkullType
    420.     getAccountNumberByName = getAccountIdByName
    421.     getIPByName = getIpByName
    422.     getPlayersByIP = getPlayersByIp
    423.     getThingfromPos = getThingFromPos
    424.     getPlayersByAccountNumber = getPlayersByAccountId
    425.     getIPByPlayerName = getIpByName
    426.     getPlayersByIPNumber = getPlayersByIp
    427.     getAccountNumberByPlayerName = getAccountIdByName
    428.     convertIntToIP = doConvertIntegerToIp
    429.     convertIPToInt = doConvertIpToInteger
    430.     queryTileAddThing = doTileQueryAdd
    431.     getTileHouseInfo = getHouseFromPos
    432.     executeRaid = doExecuteRaid
    433.     saveServer = doSaveServer
    434.     cleanHouse = doCleanHouse
    435.     cleanMap = doCleanMap
    436.     shutdown = doShutdown
    437.     mayNotMove = doCreatureSetNoMove
    438.     doPlayerSetNoMove = doCreatureSetNoMove
    439.     getPlayerNoMove = getCreatureNoMove
    440.     getConfigInfo = getConfigValue
    441.     doPlayerAddExp = doPlayerAddExperience
    442.     isInArea = isInRange
    443.     doPlayerSetSkillRate = doPlayerSetRate
    444.     getCreatureLookDir = getCreatureLookDirection
    445.     getPlayerLookDir = getCreatureLookDirection
    446.     getPlayerLookDirection = getCreatureLookDirection
    447.     doCreatureSetLookDir = doCreatureSetLookDirection
    448.     getPlayerLookPos = getCreatureLookPosition
    449.     setPlayerStamina = doPlayerSetStamina
    450.     setPlayerPromotionLevel = doPlayerSetPromotionLevel
    451.     setPlayerGroupId = doPlayerSetGroupId
    452.     setPlayerPartner = doPlayerSetPartner
    453.     setPlayerStorageValue = doPlayerSetStorageValue
    454.     setPlayerBalance = doPlayerSetBalance
    455.     doAddMapMark = doPlayerAddMapMark
    456.     doSendTutorial = doPlayerSendTutorial
    457.  
    458.     //lua-made functions
    459.     doPlayerGiveItem(cid, itemid, amount, subType)
    460.     doPlayerTakeItem(cid, itemid, amount)
    461.     doPlayerBuyItem(cid, itemid, count, cost, charges)
    462.     doPlayerBuyItemContainer(cid, containerid, itemid, count, cost, charges)
    463.     doPlayerSellItem(cid, itemid, count, cost)
    464.     doPlayerWithdrawMoney(cid, money)
    465.     doPlayerDepositMoney(cid, money)
    466.     comparePos(pos, posEx)
    467.     isInRange(pos, fromPos, toPos)
    468.     getArea(pos, rangeX, rangeY)
    469.     isPremium(cid)
    470.     getMonthDayEnding(day)
    471.     getMonthString(m)
    472.     getArticle(str)
    473.     isNumber(str)
    474.     getDistanceBetween(firstPosition, secondPosition)
    475.     doPlayerAddAddons(cid, addon)
    476.     isSorcerer(cid)
    477.     isDruid(cid)
    478.     isPaladin(cid)
    479.     isKnight(cid)
    480.     isRookie(cid)
    481.     getDirectionTo(pos, posEx)
    482.     getCreatureLookPosition(cid)
    483.     getPosByDir(fromPosition, direction, size)
    484.     doPlayerWithdrawAllMoney(cid)
    485.     doPlayerDepositAllMoney(cid)
    486.     doPlayerTransferAllMoneyTo(cid, target)
    487.     doPlayerAddLevel(cid, amount, round)
    488.     doPlayerAddMagLevel(cid, amount)
    489.     doPlayerAddSkill(cid, amount)
    490.     playerExists(name)
    491.     getTibiaTime()
    492.     doWriteLogFile(file, text)
    493.     isInArea(pos, fromPos, toPos)
    494.     getExperienceForLevel(lv)
    495.     doMutePlayer(cid, time)
    496.     getPlayerGroupName(cid)
    497.     getPlayerVocationName(cid)
    498.     getPromotedVocation(vid)
    499.     doPlayerRemovePremiumDays(cid, days)
    500.     getPlayerMasterPos(cid)
    501.     getHouseOwner(houseId)
    502.     getHouseName(houseId)
    503.     getHouseEntry(houseId)
    504.     getHouseRent(houseId)
    505.     getHousePrice(houseId)
    506.     getHouseTown(houseId)
    507.     getHouseTilesCount(houseId)
    508.     getItemNameById(itemid)
    509.     getItemPluralNameById(itemid)
    510.     getItemArticleById(itemid)
    511.     getItemName(uid)
    512.     getItemPluralName(uid)
    513.     getItemArticle(uid)
    514.     getItemText(uid)
    515.     getItemSpecialDescription(uid)
    516.     getItemWriter(uid)
    517.     getItemDate(uid)
    518.     getTilePzInfo(pos)
    519.     getTileZoneInfo(pos)
    520.     debugPrint(text)
    521.     doShutdown()
    522.     doSummonCreature(name, pos)
    523.     getOnlinePlayers()
    524.     getPlayerByName(name)
    525.     isPlayerGhost(cid)
    526.     getPlayerFrags(cid)
    527.     getPartyLeader(cid)
    528.     isInParty(cid)
    529.     isPrivateChannel(channelId)
    530.     doConvertIntegerToIp(int, mask)
    531.     doConvertIpToInteger(int, mask)
    532.     getBooleanFromString(str)
    533.     doCopyItem(item, attributes)
    534.     exhaustion.check(cid, storage)
    535.     exhaustion.get(cid, storage)
    536.     exhaustion.set(cid, storage, time)
    537.     exhaustion.make(cid, storage, time)
    538.     table.find(table, value)
    539.     table.isStrIn(txt, str)
    540.     table.countElements(table, item)
    541.     table.getCombinations(table, num)
    542.     string.split(str)
    543.     string.trim(str)
    544.     string.explode(str, sep)
     
    Last edited: Mar 23, 2010
  3. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART II - If...Else...Elseif...Return...End...(In which Order do I use them?)

    In this Part we write our first Script.
    NOTE! I wont make a Script for an Server so it will be easier to understand at the start...

    Code (Text):
    1. if My Car is repaired then -- "if" is the start of something, "then" means what will happen now.
    2.     I'll drive to work with it -- this will happen then
    3. end -- everytime you start an "if" you have to "end" it!
    this is the basic Structure of an Script...
    but what do we do if the car isn't repaired?

    Code (Text):
    1. if My Car is repaired then
    2.     I'll drive to work with it
    3. else -- "else" is used as an "single" counterpart of an "if", means basicly just that if the "if" is not true in this case the else will be read. NOTE an "else" doesn't need an extra "end"
    4.     I'll go by Bike -- this will happen if the car is still not repaired.
    5. end
    I just noticed that my brother took my bike :( so what shall we do now?

    Code (Text):
    1. if My Car is repaired then
    2.     I'll drive to work with it
    3. elseif My Bike is taken then -- This is similiar to "else" but the difference is that you can make different situations out of it. NOTE an "elseif" doesn't need an extra "end"
    4.     I'll go by Bus -- will happen when my car is still not repaired.
    5. end
    The Bus left before I came. So I'll wait for the next Bus.

    Code (Text):
    1. if My Car is repaired then
    2.     I'll drive to work with it -- happens if the car is repaired.
    3. elseif My Bike is taken then
    4.     I'll go by Bus -- happens if my bike is taken.
    5. elseif I miss the Bus then
    6.     I'll wait for the next one -- happens if i miss the buss
    7. end
    Looks quite easy doesn't it?

    Let's go for a Server Script now. (take a look at the Function List therefore)
    This Script will be a switch which gives you an message when you pull it!

    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     if item.itemid == 1945 then
    3.         doPlayerSendTextMessage(cid,21,"It works !")
    4.         doTransformItem(item.uid, item.itemid + 1)
    5.     elseif item.itemid == 1946 then
    6.         doPlayerSendTextMessage(cid,21,"You pulled it back!")
    7.         doTransformItem(item.uid, item.itemid - 1)
    8.     end
    9.     return TRUE
    10. end -- Every Function has to have an own "end" too.
    Now the explanation..You maybe ask yourself now "wtf is item.itemid etc." Let me explain that a bit.

    Code (Text):
    1. item.itemid == 1945 -- item.itemid stands for the item which we used to get the action to work, == is meant that it "equals" to the thing after. In this case 1945. (there are different types like "<"-- [I]is smaller as[/I],">"-- [I]is greater as[/I],"<="-- [I]is smaller or same as[/I],">="[I]is greater or same as[/I],"~="-- [I]is not same as[/I])
    2. cid -- This reflects the Player who is starting the action currently.
    3. 21 -- In this case it's the number which stands for an color (not really necessary to know at the moment)
    4. "it works !" -- The text which will we receive when we execute the script
    5. return TRUE -- We have to return "TRUE" because we want something to happen, if we would return "FALSE" in this case we wouldn't get a message or anything else (You can return many other things aswell not just only "TRUE" or "FALSE")
    Now you know the Basics of Scripting. Now you should be able to build a proper structure and explain what it does.
     
    Last edited: Dec 15, 2013
  4. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART III -- is greater as(>)....is smaller as(<)...is same as(==)...(How to use them correct?)


    I'm not going to explain much now since we already know now how to build a Script. So we should start with expanding our Script which we made in PART II.

    Let's say we wanna add an Level requirement on the Lever so that only lvl 50 or higher can pull it.

    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
    3.         doPlayerSendTextMessage(cid,21,"It works !")
    4.         doTransformItem(item.uid, item.itemid + 1)
    5.     elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
    6.         doPlayerSendTextMessage(cid,21,"You pulled it back!")
    7.         doTransformItem(item.uid, item.itemid - 1)
    8.     else
    9.         doPlayerSendCancel(cid,"You don't have the required level to use this.")
    10.     end
    11.     return TRUE
    12. end
    This would be the easiest way to do it in this case.

    Now we just set up some different situations, no need to make extra Scripts for this part

    Code (Text):
    1. if getPlayerLevel(cid) < 50 then -- if the Player has an lower level then 50 it will work
    2. if getPlayerLevel(cid) > 50 then -- if the Player has an higher level then 50 it will work.
    3. if getPlayerLevel(cid) <= 50 then -- if the Player has an lower or the same level as 50 it will work.
    4. if getPlayerLevel(cid) >= 50 then -- if the Player has an higher level or same level as 50 it will work.
    5. if getPlayerLevel(cid) ~= 50 then -- if the Player doesn't have level 50 then it will work.
    6. if getPlayerLevel(cid) == 50 then -- Only if the Player has level 50 then it will work.

    This should have cleared your mind now, You should be able to use them in correct order like you want them now.
     
    Last edited: Dec 15, 2013
  5. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART IV -- Local and Global Statements...(What are they for? When shall I use them?)

    Both statements look almost the same with the difference that you have to write

    Code (Text):
    1. local test = 1 -- In order to use a local statement and
    2. test = 1 -- To use the Global
    There is not much difference between them if you write them but they make a huge difference...

    "local" is used in order for just inside a Script and the "global" is used to be executed for every file depending on your server!

    Let's say it like this, if you use an "local" statement (local word = hello) then if i would write "word" in a script it would be seen as "hello" but ONLY in this Script!
    If I would use an "global" statement, then everytime I write "word" it would mean "hello".

    Question: Why shall I even use local or global statements? Isn't it easier to just write in what you want?
    Answer: No it isn't! it can save up a lot of time if you have to use same things twice or even more!

    example:

    We add that the player recovers 500 mana/hp

    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
    3.         doPlayerSendTextMessage(cid,21,"It works !")
    4.         doTransformItem(item.uid, item.itemid + 1)
    5.         doCreatureAddMana(cid,500)
    6.         doCreatureAddHealth(cid,500)
    7.     elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
    8.         doPlayerSendTextMessage(cid,21,"You pulled it back!")
    9.         doTransformItem(item.uid, item.itemid - 1)
    10.         doCreatureAddMana(cid,500)
    11.         doCreatureAddHealth(cid,500)
    12.     else
    13.         doPlayerSendCancel(cid,"You don't have the required level to use this.")
    14.     end
    15.     return TRUE
    16. end
    Seems fine...but what if I want to change the ammount to 750 now? I would have to edit every single number again...
    This is basicly why we use local/global statements.

    example:

    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2. local gain = 750
    3.     if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
    4.         doPlayerSendTextMessage(cid,21,"It works !")
    5.         doTransformItem(item.uid, item.itemid + 1)
    6.         doCreatureAddMana(cid,gain)
    7.         doCreatureAddHealth(cid,gain)
    8.     elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
    9.         doPlayerSendTextMessage(cid,21,"You pulled it back!")
    10.         doTransformItem(item.uid, item.itemid - 1)
    11.         doCreatureAddMana(cid,gain)
    12.         doCreatureAddHealth(cid,gain)
    13.     else
    14.         doPlayerSendCancel(cid,"You don't have the required level to use this.")
    15.     end
    16.     return TRUE
    17. end
    So if I would like to change the number now again I would just have to change the number behind the statement!
     
    Last edited: Dec 15, 2013
  6. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART V -- For loops...(How do I use them? In which case are they suited the best?)

    Here we are to take a first look at loops.
    They are maybe confusing at the first time but from time to time you will get used to them.
    For loops are most suited for a combination of loop and table, I'll show that in a later part.

    For loops are basicly nothing different then a counter, they start at one point and stop on a different.
    It is a bit hard to explain that (atleast for me) that is why I am going for an example and comment it, I think that is a way better explained then writing 200 lines about it.

    example:
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     for var = 1,10 do -- "var" stands for the variable of the two numbers (you can change the variable to others aswell), "1,10" means it's going to loop from 1 to 10 (10 loops in this case)
    3.         print(var) -- will print "1 2 3 4 5 6 7 8 9 10"
    4.     end
    5.     return true
    6. end
    7.  
    each for loop has to have it's own variable, you can't do it like this:
    Code (Text):
    1. for var = -1,-10 and var = 1,10 do
    correct version:
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     for a = -1,-10 and b = 1,10 do -- numbers can either be negative or positive, that doesn't matter, you can also loop from negative to positive and vice versa.
    3.         print(a ..', ' .. b ..'' || ') -- will print "-1, 1 || -2, 2 ||......"
    4.     end
    5.     return true
    6. end
    As you can see a for loop aint so hard to setup and use.

    Let's go for another example to see how it works in a server based script.

    Let's say we want to add the player a backpack and that backpack contains 3 times the same item.
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2. local backpack = doPlayerAddItem(cid, 1988, 1)
    3.     for a = 1,3 do
    4.         doAddContainerItem(backpack, 2160, 100)
    5.     end
    6.     return true
    7. end
    There's not really much more to say about the for loops.
    We'll get back to them later on.
     
    Last edited: Dec 15, 2013
  7. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART VI -- While Loops...(How do I use them? In which case are they suited the best?)

    While loops are pretty easily explained, as you may expected this loop will do something until the statement is what you want it to be.
    Simple called "while" loop.

    example:
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2.     while getPlayerLevel(cid) < 50 do
    3.         doPlayerSendTextMessage(cid,22,"You are under level 50!")
    4.     end
    5.     return true
    6. end
    7.  
    this will keep repeating to give the player the message "You are under level 50!" until he reached level 50.

    another case of usage would be like this (would be a similiar usage as a for loop)

    example:
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2. local var = 0
    3.     while var ~= 5 do
    4.         doPlayerSendTextMessage(cid,22,"var has not reached 5 yet!")
    5.         var = var + 1
    6.     end
    7.     return true
    8. end
    This is all for it, it's as easy as it's explained up there.
     
    Last edited: Dec 15, 2013
  8. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    PART VII -- Repeat Loops...(How do I use them? In which case are they suited the best?)

    Repeat loops are basicly the same as "while" loops.
    the difference is just that on a repeat loop, the loop is firstly started (and executed atleast once) and then afterwards the condition is checked.

    example:
    Code (Text):
    1. function onUse(cid, item, fromPosition, itemEx, toPosition)
    2. local loop = 0
    3.     repeat
    4.         doPlayerSendTextMessage(cid, 22, "still looping.")
    5.         loop = loop + 1
    6.     until loop > 2
    7.         return true
    8. end
    This is probably the loop which you wont be using that much.
     
    Last edited: Dec 15, 2013
    Shadow Dan and Shyrriro like this.
  9. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    spaceholder~
     
    MadMOOK likes this.
  10. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    spaceholder~
     
    MadMOOK likes this.
  11. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    spaceholder~ done :D
     
  12. Diazapam

    Diazapam !ROFLMAO!

    Joined:
    Jul 29, 2009
    Messages:
    1,411
    Likes Received:
    9
    Best Answers:
    0
    Hmm, could become very nice.

    I'll watch it ;)
     
  13. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    I still have some work to do, that it's completly finished.

    but it'll even grow bigger from time to time, since there's a lot more to teach to beginners :p
     
    Exmortis likes this.
  14. Xenios

    Xenios Well-Known Member

    Joined:
    May 28, 2007
    Messages:
    3,449
    Likes Received:
    51
    Best Answers:
    0
    Thanks for your contribution, this is going to be the most helpful tutorial for LUA scripting. :)
     
  15. Strasxni

    Strasxni

    Joined:
    Mar 13, 2010
    Messages:
    778
    Likes Received:
    11
    Best Answers:
    0
    I got your old tutorial in bookmarks, i will got this one too! Thanks a lot, this is very helpfull!
     
  16. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    I hope so :p

    I'm glad to hear that :D
     
    Huli likes this.
  17. Znote

    Znote <?php echo $title; ?> Staff Member Global Moderator Premium User

    Joined:
    Feb 14, 2008
    Messages:
    6,071
    Likes Received:
    868
    Best Answers:
    86
    Yep, definitely bookmarked! ;)

    Thanks for your contribution =D
     
  18. Strasxni

    Strasxni

    Joined:
    Mar 13, 2010
    Messages:
    778
    Likes Received:
    11
    Best Answers:
    0
  19. Diazapam

    Diazapam !ROFLMAO!

    Joined:
    Jul 29, 2009
    Messages:
    1,411
    Likes Received:
    9
    Best Answers:
    0
    Link me his old tutorial ;)

    I'm getting quite impressed by this.
     
  20. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    Likes Received:
    444
    Best Answers:
    0
    Well the first 4 parts are based on my old, you can find the link at the first post, I've added it.
     

Share This Page

Loading...