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
    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
    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:

    [lua]function onUse(cid, item, fromPosition, itemEx, toPosition)
    function onStepIn(cid, item, frompos, itemEx, topos)
    function onStepOut(cid, item, frompos, itemEx, topos)
    function onSay(cid, words, param)
    function onEquip(cid, item, slot)
    function onDeEquip(cid, item, slot)
    function onAddItem(cid, moveitem, tileitem, position)
    function onRemoveItem(cid, moveitem, tileitem, position)[/lua]

    Creaturescripts:

    [lua]function onLogin(cid)
    function onLogout(cid)
    function onJoinChannel(cid, channel, users)
    function onLeaveChannel(cid, channel, users)
    function onAdvance(cid, skill, oldLevel, newLevel)
    function onLook(cid, thing, position, lookDistance)
    function onSendMail((cid, receiver, open, itemBox)
    function onReceiveMail(cid, sender, open, itemBox)
    function onTradeRequest(cid, target, item)
    function onTradeAccept(cid, target, item)
    function onTextEdit(cid, item, newText)
    function onReportBug(cid, comment)
    function onThink(cid, interval)
    function onDirection(cid, old, current)
    function onOutfit(cid, old, current)
    function onStatsChange(cid, attacker, type, combat, value)
    function onAreaCombat(cid, ground, position, aggressive)
    function onPush(cid, target)
    function onTarget(cid, target)
    function onFollow(cid, target)
    function onCombat(cid, target)
    function onAttack(cid, target)
    function onCast(cid, target)
    function onKill(cid, target, damage, flags)
    function onDeath(cid, corpse, deathList)
    function onPreprareDeath(cid, deathList)
    [/lua]

    Globalevents:

    [lua]function onStartUp()
    function onShutdown()
    function onGlobalSave()
    function onRecord(current, old, cid)
    function onTime(time)
    function onThink(interval)[/lua]

    Those are the Functions which the Updated Distros have so far.

    Let me explain you each function now...

    [lua]function onUse(cid, item, fromPosition, itemEx, toPosition)[/lua]

    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.


    [lua]function onStepIn(cid, item, frompos, itemEx, topos)[/lua]

    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.


    [lua]function onStepOut(cid, item, frompos, itemEx, topos)[/lua]

    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.


    [lua]function onSay(cid, words, param)[/lua]

    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.


    [lua]function onEquip(cid, item, slot)[/lua]

    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.


    [lua]function onDeEquip(cid, item, slot)[/lua]

    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.


    [lua]function onAddItem(cid, moveitem, tileitem, position)[/lua]

    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.

    [lua]function onRemoveItem(cid, moveitem, tileitem, position)[/lua]

    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
    [lua]//get*
    getCreatureHealth(cid)
    getCreatureMaxHealth(cid)
    getCreatureHideHealth(cid)
    getCreatureMana(cid)
    getCreatureMaxMana(cid)
    getCreatureSpeakType(cid)
    getCreatureMaster(cid)
    getCreatureSummons(cid)
    getCreatureOutfit(cid)
    getCreaturePosition(cid)
    getCreatureLookDirection(cid)
    getCreatureName(cid)
    getCreatureSpeed(cid) //TODO
    getCreatureBaseSpeed(cid) //TODO
    getCreatureTarget(cid) //TODO
    getCreatureByName(name)
    getCreatureSkullType(cid)
    getCreatureCondition(cid, condition[, subId]) //TODO
    getCreatureNoMove(cid) //TODO
    getMonsterInfo(name)
    getMonsterHealingSpells(name) //TODO
    getMonsterAttackSpells(name) //TODO
    getMonsterLootList(name) //TODO
    getMonsterSummonList(name) //TODO
    getMonsterTargetList(cid) //TODO
    getMonsterFriendList(cid) //TODO
    getPlayerByNameWildcard(name~[, ret = false]) //TODO
    getPlayerLossSkill(cid) //TODO
    getPlayerLossPercent(cid, lossType) //TODO
    getPlayerGUIDByName(name[, multiworld = false]) //TODO
    getPlayerNameByGUID(guid[, multiworld = false[, displayError = true]]) //TODO
    getPlayerFood(cid)
    getPlayerLevel(cid)
    getPlayerExperience(cid)
    getPlayerMagLevel(cid[, ignoreBuffs = false]) //TODO
    getPlayerSpentMana(cid) //TODO
    getPlayerAccess(cid)
    getPlayerGhostAccess(cid)
    getPlayerSkillLevel(cid, skillId)
    getPlayerSkillTries(cid, skillId) //TODO
    getPlayerTown(cid)
    getPlayerVocation(cid)
    getPlayerRequiredMana(cid, magicLevel) //TODO
    getPlayerRequiredSkillTries(cid, skillId, skillLevel) //TODO
    getPlayerItemCount(cid, itemid[, subType = -1])
    getPlayerSoul(cid)
    getPlayerAccountId(cid) //TODO
    getPlayerAccount(cid) //TODO
    getPlayerIp(cid) //TODO
    getPlayerFreeCap(cid)
    getPlayerLight(cid)
    getPlayerSlotItem(cid, slot)
    getPlayerWeapon(cid[, ignoreAmmo = false]) //TODO
    getPlayerItemById(cid, deepSearch, itemId[, subType = -1]) //TODO
    getPlayerDepotItems(cid, depotid)
    getPlayerGuildId(cid)
    getPlayerGuildName(cid)
    getPlayerGuildRank(cid)
    getPlayerGuildNick(cid)
    getPlayerGuildLevel(cid) //TODO: From here, all bottoms
    getPlayerSex(cid)
    getPlayerStorageValue(uid, key)
    getPlayerGUID(cid)
    getPlayerFlagValue(cid, flag)
    getPlayerCustomFlagValue(cid, flag)
    getPlayerPromotionLevel(cid)
    getPlayerGroupId(cid)
    getPlayerLearnedInstantSpell(cid, name)
    getPlayerInstantSpellCount(cid)
    getPlayerInstantSpellInfo(cid, index)
    getPlayerBlessing(cid, blessing)
    getPlayerStamina(cid)
    getPlayerExtraExpRate(cid)
    getPlayerPartner(cid)
    getPlayerParty(cid)
    getPlayerPremiumDays(cid)
    getPlayerBalance(cid)
    getPlayerMoney(cid)
    getPlayerSkullTicks(cid, type)
    getPlayerRates(cid)
    getPlayerLastLogin(cid)
    getPlayerLastLoginSaved(cid)
    getPlayerAccountManager(cid)
    getInstantSpellInfo(cid, name)
    getPlayersByAccountId(accountNumber)
    getPlayersByIp(ip[, mask = 0xFFFFFFFF])
    getChannelUsers(channelId)
    getPlayersOnline()
    getPartyMembers(lid)
    getAccountIdByName(name)
    getAccountByName(name)
    getAccountIdByAccount(accName)
    getAccountByAccountId(accId)
    getIpByName(name)
    getItemRWInfo(uid)
    getItemProtection(uid)
    getItemDescriptionsById(itemid)
    getItemWeightById(itemid, count[, precise])
    getItemDescriptions(uid)
    getItemWeight(uid[, precise])
    getItemAttack(uid)
    getItemExtraAttack(uid)
    getItemDefense(uid)
    getItemExtraDefense(uid)
    getItemArmor(uid)
    getItemAttackSpeed(uid)
    getItemHitChance(uid)
    getItemShootRange(uid)
    getItemIdByName(name[, displayError = true])
    getItemLevelDoor(itemid)
    getItemWeaponType(uid)
    getFluidSourceType(type)
    getContainerSize(uid)
    getContainerCap(uid)
    getContainerCapById(itemid)
    getContainerItem(uid, slot)
    getDepotId(uid)
    getTileItemById(pos, itemId[, subType = -1])
    getTileItemByType(pos, type)
    getTileThingByPos(pos)
    getTileInfo(pos)
    getTopCreature(pos)
    getClosestFreeTile(cid, targetpos[, extended = false[, ignoreHouse = true]])
    getThingFromPos(pos)
    getThing(uid)
    getThingPos(uid)
    getHouseInfo(id)
    getHouseAccessList(houseid, listid)
    getHouseByPlayerGUID(playerGUID)
    getHouseFromPos(pos)
    getTownId(townName)
    getTownName(townId)
    getTownTemplePosition(townId)
    getTownHouses(townId)
    getWorldType()
    getWorldTime()
    getWorldLight()
    getWorldCreatures(type) //0 players, 1 monsters, 2 npcs, 3 all
    getWorldUpTime()
    getHighscoreString(skillId)
    getVocationInfo(id)
    getGuildId(guildName)
    getGuildMotd(guildId)
    getSpectators(centerPos, rangex, rangey[, multifloor = false])
    getSearchString(fromPosition, toPosition[, fromIsCreature = false[, toIsCreature = false]])
    getWaypointPosition(name)
    getGameState()
    getNotationsCount(accId)
    getBanData(value)
    getBanList(type[, value])
    getBanReason(id)
    getBanAction(id[, ipBanishment])
    getGlobalStorageValue(valueid)
    getExperienceStage(level)
    getConfigFile()
    getConfigValue(key)
    getModList()
    loadmodlib(libName)
    domodlib(libName)
    getLogsDir()
    getDataDir()
    getWaypointList()
    getTalkActionList()
    getExperienceStageList()

    //set*
    setCreatureMaxHealth(cid, health)
    setCreatureMaxMana(cid, mana)
    setHouseOwner(houseid, ownerGUID)
    setHouseAccessList(houseid, listid, listtext)
    setItemName(uid)
    setItemPluralName(uid)
    setItemArticle(uid)
    setItemAttack(uid, attack)
    setItemExtraAttack(uid, extraattack)
    setItemDefense(uid, defense)
    setItemArmor(uid, armor)
    setItemExtraDefense(uid, extradefense)
    setItemAttackSpeed(uid, attackspeed)
    setItemHitChance(uid, hitChance)
    setItemShootRange(uid, shootRange)
    setCombatArea(combat, area)
    setCombatCondition(combat, condition)
    setCombatParam(combat, key, value)
    setConditionParam(condition, key, value)
    setCombatCallBack(combat, key, function_name)
    setCombatFormula(combat, type, mina, minb, maxa, maxb)
    setConditionFormula(combat, mina, minb, maxa, maxb)
    setGlobalStorageValue(key, newValue)
    setWorldType(type)

    //do*
    doCreatureAddHealth(cid, health[, force])
    doCreatureAddMana(cid, mana)
    doCreatureSetDropLoot(cid, doDrop)
    doCreatureSetSkullType(cid, skull)
    doCreatureSetSpeakType
    doCreatureSetLookDirection(cid, dir)
    doPlayerSetMaxCapacity(cid, cap)
    doCreatureChangeOutfit(cid, outfit)
    doCreatureSay(uid, text, type[, ghost = false[, cid = 0[, pos]]])
    doCreatureSetNoMove(cid, cannotMove)
    doSetCreatureLight(cid, lightLevel, lightColor, time)
    doSetCreatureOutfit(cid, outfit, time)
    doRemoveCreature(cid[, executeLogout = true])
    doMoveCreature(cid, direction)
    doConvinceCreature(cid, target)
    doChallengeCreature(cid, target)
    doChangeSpeed(cid, delta)
    doSummonMonster(name, pos)
    doCreateMonster(name, pos)
    doMonsterChangeTarget(cid)
    doMonsterSetTarget(cid, target)
    doCreateNpc(name, pos)
    doSetMonsterOutfit(cid, name, time)
    doPlayerBroadcastMessage(cid, message[, type])
    doPlayerSetSex(cid, newSex)
    doPlayerSetTown(cid, townid)
    doPlayerSetVocation(cid, voc)
    doPlayerSetStorageValue(uid, key, newValue)
    doPlayerSetGroupId(cid, newGroupId)
    doPlayerSetPromotionLevel(cid, level)
    doPlayerSetStamina(cid, minutes)
    doPlayerSetBalance(cid, balance)
    doPlayerSetExtraExpRate(cid, value)
    doPlayerSetPartner(cid, guid)
    doPlayerRemoveItem(cid, itemid, count[, subtype])
    doPlayerAddExperience(cid, amount)
    doPlayerSetGuildId(cid, id)
    doPlayerSetGuildRank(cid, rank)
    doPlayerSetGuildNick(cid, nick)
    doPlayerAddOutfit(cid,looktype, addons)
    doPlayerRemoveOutfit(cid,looktype, addons)
    doPlayerSetRedSkullTicks(cid, amount)
    doPlayerSetLossPercent(cid, lossType, newPercent)
    doPlayerSetLossSkill(cid, doLose)
    doPlayerAddSkillTry(cid, skillid, n)
    doPlayerAddSpentMana(cid, amount)
    doPlayerAddSoul(cid, soul)
    doPlayerAddItem(uid, itemid[, count/subtype[, canDropOnMap = true]])
    doPlayerAddItemEx(cid, uid[, canDropOnMap = false])
    doPlayerSendTextMessage(cid, MessageClasses, message)
    doPlayerSendChannelMessage(cid, author, message, SpeakClasses, channel)
    doPlayerSendToChannel(cid, targetId, SpeakClasses, message, channel[, time])
    doPlayerAddMoney(cid, money)
    doPlayerRemoveMoney(cid, money)
    doPlayerTransferMoneyTo(cid, target, money)
    doPlayerPopupFYI(cid, message)
    doPlayerSendTutorial(cid, id)
    doPlayerAddMapMark(cid, pos, type[, description])
    doPlayerAddPremiumDays(cid, days)
    doPlayerAddBlessing(cid, blessing)
    doPlayerAddStamina(cid, minutes)
    doPlayerResetIdleTime(cid)
    doPlayerLearnInstantSpell(cid, name)
    doPlayerUnlearnInstantSpell(cid, name)
    doPlayerFeed(cid, food)
    doPlayerSendCancel(cid, text)
    doPlayerSendDefaultCancel(cid, ReturnValue)
    doPlayerSetRate(cid, type, value)
    doPlayerJoinParty(cid, lid)
    doPlayerSendOutfitWindow(cid)
    doPlayerSave(cid[, shallow = false])
    doCreateItem(itemid, type/count, pos)
    doCreateItemEx(itemid[, count/subtype])
    doAddContainerItemEx(uid, virtuid)
    doAddContainerItem(uid, itemid[, count/subtype])
    doChangeTypeItem(uid, newtype)
    doDecayItem(uid)
    doRemoveItem(uid[, count])
    doTransformItem(uid, toitemid[, count/subtype])
    doSetItemActionId(uid, actionid)
    doSetItemText(uid, text[, writer[, date]])
    doSetItemSpecialDescription(uid, desc)
    doSetItemOutfit(cid, item, time)
    doSetItemProtection(uid, value)
    doTileAddItemEx(pos, uid)
    doTileQueryAdd(uid, pos[, flags])
    doAddCondition(cid, condition)
    doRemoveCondition(cid, type[, subId])
    doRemoveConditions(cid[, onlyPersistent])
    doAreaCombatHealth(cid, type, pos, area, min, max, effect)
    doTargetCombatHealth(cid, target, type, min, max, effect)
    doAreaCombatMana(cid, pos, area, min, max, effect)
    doTargetCombatMana(cid, target, min, max, effect)
    doAreaCombatCondition(cid, pos, area, condition, effect)
    doTargetCombatCondition(cid, target, condition, effect)
    doAreaCombatDispel(cid, pos, area, type, effect)
    doTargetCombatDispel(cid, target, type, effect)
    doCombat(cid, combat, param)
    doTeleportThing(cid, newpos[, pushmove = true])
    doCreateTeleport(itemid, topos, createpos)
    doSendMagicEffect(pos, type[, player])
    doSendDistanceShoot(frompos, topos, type[, player])
    doSendAnimatedText(pos, text, color[, player])
    doShowTextDialog(cid, itemid, text)
    doRelocate(pos, toPos[, creatures = true])
    doBroadcastMessage(message, type)
    doWaypointAddTemporial(name, pos)
    doSetGameState(stateId)
    doAddIpBanishment(ip[, length[, comment[, admin]]])
    doAddNamelock(name[, reason[, action[, comment[, admin]]]])
    doAddBanishment(accId[, length[, reason[, action[, comment[, admin]]]]])
    doAddDeletion(accId[, reason[, action[, comment[, admin]]]]])
    doAddNotation(accId[, reason[, action[, comment[, admin]]]]])
    doRemoveIpBanishment(ip[, mask])
    doRemoveNamelock(name)
    doRemoveBanisment(accId)
    doRemoveDeletion(accId)
    doRemoveNotations(accId)
    doSaveServer()
    doReloadInfo(id[, cid])
    doCleanHouse(houseId)
    doCleanMap()
    doRefreshMap()

    //is*
    isCreature(cid)
    isMonster(uid)
    isNpc(uid)
    isPlayer(cid)
    isPlayerPzLocked(cid)
    isItemStackable(itemid)
    isItemRune(itemid)
    isItemMovable(itemid)
    isItemDoor(itemid)
    isItemContainer(itemid)
    isItemFluidContainer(itemid)
    isContainer(uid)
    isCorpse(uid)
    isMovable(uid)
    isSightClear(fromPos, toPos, floorCheck)
    isIpBanished(ip[, mask])
    isPlayerNamelocked(name)
    isAccountBanished(accId)
    isAccountDeleted(accId)
    isInArray({array}, value[, lower = true])

    //others
    registerCreatureEvent(uid, eventName)
    createCombatArea({area}[, {exArea}])
    createConditionObject(type[, ticks[, buff[, subId]]])
    addDamageCondition(condition, rounds, time, value)
    addOutfitCondition(condition, lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet)
    createCombatObject()
    numberToVariant(number)
    stringToVariant(string)
    positionToVariant(pos)
    targetPositionToVariant(pos)
    variantToNumber(var)
    variantToString(var)
    variantToPosition(var)
    canPlayerWearOutfit(cid, lookType, addons)
    executeRaid(name)
    addEvent(callback, delay, ...)
    stopEvent(eventid)
    hasProperty(uid)

    md5(str)
    sha1(str)

    //db table
    db.executeQuery(query)
    db.storeQuery(query)
    db.escapeString(str)
    db.escapeBlob(s, length)
    db.stringComparisonOperator()
    db.lastInsertId()

    //result table
    result.getDataInt(resId, s)
    result.getDataLong(resId, s)
    result.getDataString(resId, s)
    result.getDataStream(resId, s, length)
    result.next(resId)
    result.free(resId)

    //bit table
    #bit.cast
    bit.bnot(n)
    bit.band(type, n)
    bit.bor(type, n)
    bit.bxor(type, n)
    bit.lshift(type, n)
    bit.rshift(type, n)
    #bit.arshift
    #bit.ucast
    bit.ubnot(n)
    bit.uband(type, n)
    bit.ubor(type, n)
    bit.ubxor(type, n)
    bit.ulshift(type, n)
    bit.urshift(type, n)
    #bit.uarshift

    //compats
    table.getPos = table.find
    doSetCreatureDropLoot = doCreatureSetDropLoot
    doPlayerSay = doCreatureSay
    doPlayerAddMana = doCreatureAddMana
    playerLearnInstantSpell = doPlayerLearnInstantSpell
    doPlayerRemOutfit = doPlayerRemoveOutfit
    pay = doPlayerRemoveMoney
    broadcastMessage = doBroadcastMessage
    getPlayerName = getCreatureName
    getPlayerPosition = getCreaturePosition
    getCreaturePos = getCreaturePosition
    creatureGetPosition = getCreaturePosition
    getPlayerMana = getCreatureMana
    getPlayerMaxMana = getCreatureMaxMana
    hasCondition = getCreatureCondition
    isMoveable = isMovable
    isItemMoveable = isItemMovable
    saveData = saveServer
    savePlayers = saveServer
    getPlayerSkill = getPlayerSkillLevel
    getPlayerSkullType = getCreatureSkullType
    getCreatureSkull = getCreatureSkullType
    getAccountNumberByName = getAccountIdByName
    getIPByName = getIpByName
    getPlayersByIP = getPlayersByIp
    getThingfromPos = getThingFromPos
    getPlayersByAccountNumber = getPlayersByAccountId
    getIPByPlayerName = getIpByName
    getPlayersByIPNumber = getPlayersByIp
    getAccountNumberByPlayerName = getAccountIdByName
    convertIntToIP = doConvertIntegerToIp
    convertIPToInt = doConvertIpToInteger
    queryTileAddThing = doTileQueryAdd
    getTileHouseInfo = getHouseFromPos
    executeRaid = doExecuteRaid
    saveServer = doSaveServer
    cleanHouse = doCleanHouse
    cleanMap = doCleanMap
    shutdown = doShutdown
    mayNotMove = doCreatureSetNoMove
    doPlayerSetNoMove = doCreatureSetNoMove
    getPlayerNoMove = getCreatureNoMove
    getConfigInfo = getConfigValue
    doPlayerAddExp = doPlayerAddExperience
    isInArea = isInRange
    doPlayerSetSkillRate = doPlayerSetRate
    getCreatureLookDir = getCreatureLookDirection
    getPlayerLookDir = getCreatureLookDirection
    getPlayerLookDirection = getCreatureLookDirection
    doCreatureSetLookDir = doCreatureSetLookDirection
    getPlayerLookPos = getCreatureLookPosition
    setPlayerStamina = doPlayerSetStamina
    setPlayerPromotionLevel = doPlayerSetPromotionLevel
    setPlayerGroupId = doPlayerSetGroupId
    setPlayerPartner = doPlayerSetPartner
    setPlayerStorageValue = doPlayerSetStorageValue
    setPlayerBalance = doPlayerSetBalance
    doAddMapMark = doPlayerAddMapMark
    doSendTutorial = doPlayerSendTutorial

    //lua-made functions
    doPlayerGiveItem(cid, itemid, amount, subType)
    doPlayerTakeItem(cid, itemid, amount)
    doPlayerBuyItem(cid, itemid, count, cost, charges)
    doPlayerBuyItemContainer(cid, containerid, itemid, count, cost, charges)
    doPlayerSellItem(cid, itemid, count, cost)
    doPlayerWithdrawMoney(cid, money)
    doPlayerDepositMoney(cid, money)
    comparePos(pos, posEx)
    isInRange(pos, fromPos, toPos)
    getArea(pos, rangeX, rangeY)
    isPremium(cid)
    getMonthDayEnding(day)
    getMonthString(m)
    getArticle(str)
    isNumber(str)
    getDistanceBetween(firstPosition, secondPosition)
    doPlayerAddAddons(cid, addon)
    isSorcerer(cid)
    isDruid(cid)
    isPaladin(cid)
    isKnight(cid)
    isRookie(cid)
    getDirectionTo(pos, posEx)
    getCreatureLookPosition(cid)
    getPosByDir(fromPosition, direction, size)
    doPlayerWithdrawAllMoney(cid)
    doPlayerDepositAllMoney(cid)
    doPlayerTransferAllMoneyTo(cid, target)
    doPlayerAddLevel(cid, amount, round)
    doPlayerAddMagLevel(cid, amount)
    doPlayerAddSkill(cid, amount)
    playerExists(name)
    getTibiaTime()
    doWriteLogFile(file, text)
    isInArea(pos, fromPos, toPos)
    getExperienceForLevel(lv)
    doMutePlayer(cid, time)
    getPlayerGroupName(cid)
    getPlayerVocationName(cid)
    getPromotedVocation(vid)
    doPlayerRemovePremiumDays(cid, days)
    getPlayerMasterPos(cid)
    getHouseOwner(houseId)
    getHouseName(houseId)
    getHouseEntry(houseId)
    getHouseRent(houseId)
    getHousePrice(houseId)
    getHouseTown(houseId)
    getHouseTilesCount(houseId)
    getItemNameById(itemid)
    getItemPluralNameById(itemid)
    getItemArticleById(itemid)
    getItemName(uid)
    getItemPluralName(uid)
    getItemArticle(uid)
    getItemText(uid)
    getItemSpecialDescription(uid)
    getItemWriter(uid)
    getItemDate(uid)
    getTilePzInfo(pos)
    getTileZoneInfo(pos)
    debugPrint(text)
    doShutdown()
    doSummonCreature(name, pos)
    getOnlinePlayers()
    getPlayerByName(name)
    isPlayerGhost(cid)
    getPlayerFrags(cid)
    getPartyLeader(cid)
    isInParty(cid)
    isPrivateChannel(channelId)
    doConvertIntegerToIp(int, mask)
    doConvertIpToInteger(int, mask)
    getBooleanFromString(str)
    doCopyItem(item, attributes)
    exhaustion.check(cid, storage)
    exhaustion.get(cid, storage)
    exhaustion.set(cid, storage, time)
    exhaustion.make(cid, storage, time)
    table.find(table, value)
    table.isStrIn(txt, str)
    table.countElements(table, item)
    table.getCombinations(table, num)
    string.split(str)
    string.trim(str)
    string.explode(str, sep)[/lua]
     
    Last edited: Mar 23, 2010
  3. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    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:
    if My Car is repaired then -- "if" is the start of something, "then" means what will happen now.
        I'll drive to work with it -- this will happen then
    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:
    if My Car is repaired then
        I'll drive to work with it
    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"
        I'll go by Bike -- this will happen if the car is still not repaired.
    end
    I just noticed that my brother took my bike :( so what shall we do now?

    Code:
    if My Car is repaired then
        I'll drive to work with it
    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"
        I'll go by Bus -- will happen when my car is still not repaired.
    end
    The Bus left before I came. So I'll wait for the next Bus.

    Code:
    if My Car is repaired then
        I'll drive to work with it -- happens if the car is repaired.
    elseif My Bike is taken then
        I'll go by Bus -- happens if my bike is taken.
    elseif I miss the Bus then
        I'll wait for the next one -- happens if i miss the buss
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        if item.itemid == 1945 then
            doPlayerSendTextMessage(cid,21,"It works !")
            doTransformItem(item.uid, item.itemid + 1)
        elseif item.itemid == 1946 then
            doPlayerSendTextMessage(cid,21,"You pulled it back!")
            doTransformItem(item.uid, item.itemid - 1)
        end
        return TRUE
    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:
    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])
    cid -- This reflects the Player who is starting the action currently.
    21 -- In this case it's the number which stands for an color (not really necessary to know at the moment)
    "it works !" -- The text which will we receive when we execute the script
    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
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"It works !")
            doTransformItem(item.uid, item.itemid + 1)
        elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"You pulled it back!")
            doTransformItem(item.uid, item.itemid - 1)
        else
            doPlayerSendCancel(cid,"You don't have the required level to use this.")
        end
        return TRUE
    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:
    if getPlayerLevel(cid) < 50 then -- if the Player has an lower level then 50 it will work
    if getPlayerLevel(cid) > 50 then -- if the Player has an higher level then 50 it will work.
    if getPlayerLevel(cid) <= 50 then -- if the Player has an lower or the same level as 50 it will work.
    if getPlayerLevel(cid) >= 50 then -- if the Player has an higher level or same level as 50 it will work.
    if getPlayerLevel(cid) ~= 50 then -- if the Player doesn't have level 50 then it will work.
    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
    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:
    local test = 1 -- In order to use a local statement and
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"It works !")
            doTransformItem(item.uid, item.itemid + 1)
            doCreatureAddMana(cid,500)
            doCreatureAddHealth(cid,500)
        elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"You pulled it back!")
            doTransformItem(item.uid, item.itemid - 1)
            doCreatureAddMana(cid,500)
            doCreatureAddHealth(cid,500)
        else
            doPlayerSendCancel(cid,"You don't have the required level to use this.")
        end
        return TRUE
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
    local gain = 750
        if item.itemid == 1945 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"It works !")
            doTransformItem(item.uid, item.itemid + 1)
            doCreatureAddMana(cid,gain)
            doCreatureAddHealth(cid,gain)
        elseif item.itemid == 1946 and getPlayerLevel(cid) >= 50 then
            doPlayerSendTextMessage(cid,21,"You pulled it back!")
            doTransformItem(item.uid, item.itemid - 1)
            doCreatureAddMana(cid,gain)
            doCreatureAddHealth(cid,gain)
        else
            doPlayerSendCancel(cid,"You don't have the required level to use this.")
        end
        return TRUE
    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
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        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)
            print(var) -- will print "1 2 3 4 5 6 7 8 9 10"
        end
        return true
    end
    
    each for loop has to have it's own variable, you can't do it like this:
    Code:
    for var = -1,-10 and var = 1,10 do
    correct version:
    Code:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        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.
            print(a ..', ' .. b ..'' || ') -- will print "-1, 1 || -2, 2 ||......"
        end
        return true
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
    local backpack = doPlayerAddItem(cid, 1988, 1)
        for a = 1,3 do
            doAddContainerItem(backpack, 2160, 100)
        end
        return true
    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
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
        while getPlayerLevel(cid) < 50 do
            doPlayerSendTextMessage(cid,22,"You are under level 50!")
        end
        return true
    end
    
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
    local var = 0
        while var ~= 5 do
            doPlayerSendTextMessage(cid,22,"var has not reached 5 yet!")
            var = var + 1
        end
        return true
    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
    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:
    function onUse(cid, item, fromPosition, itemEx, toPosition)
    local loop = 0
        repeat
            doPlayerSendTextMessage(cid, 22, "still looping.")
            loop = loop + 1
        until loop > 2
            return true
    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
    spaceholder~
     
    MadMOOK likes this.
  10. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    spaceholder~
     
    MadMOOK likes this.
  11. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    spaceholder~ done :D
     
  12. Diazapam

    Diazapam !ROFLMAO!

    Joined:
    Jul 29, 2009
    Messages:
    1,411
    Hmm, could become very nice.

    I'll watch it ;)
     
  13. Evil Hero

    Evil Hero Legacy Member

    Joined:
    Dec 12, 2007
    Messages:
    1,082
    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,450
    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
    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
    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:
    5,930
    Yep, definitely bookmarked! ;)

    Thanks for your contribution =D
     
  18. Strasxni

    Strasxni

    Joined:
    Mar 13, 2010
    Messages:
    778
  19. Diazapam

    Diazapam !ROFLMAO!

    Joined:
    Jul 29, 2009
    Messages:
    1,411
    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
    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