• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

TFS - buying runes

revion

New Member
Joined
Oct 27, 2009
Messages
46
Reaction score
0
Hello
I would like my NPCs to sell runes like when you are saying '50 sd' then selling sd rune with 50 charges, because right now when I say "50 sd" it sells me 50 runes with 1 charge.
Could someone fix it?
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talkState = {}

function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end

local shopModule = ShopModule:new()
npcHandler:addModule(shopModule)

shopModule:addBuyableItem({'spellbook'}, 2175, 150, 'spellbook')
shopModule:addBuyableItem({'magic lightwand'}, 2163, 400, 'magic lightwand')


shopModule:addBuyableItem({'instense healing'}, 2265, 95, 1, 'intense healing rune')
shopModule:addBuyableItem({'uh'}, 2273, 10000, 100, '100 ultimate healing rune')
shopModule:addBuyableItem({'magic wall'}, 2293, 10000, 100, '100 magic wall rune')
shopModule:addBuyableItem({'destroy field'}, 2261, 45, 3, 'destroy field rune')
shopModule:addBuyableItem({'light magic missile'}, 2287, 40, 10, 'light magic missile rune')
shopModule:addBuyableItem({'hmm'}, 2311, 2000, 100, '100 heavy magic missile rune')
shopModule:addBuyableItem({'gfb'}, 2304, 2500, 100, '100 great fireball rune')
shopModule:addBuyableItem({'explosion'}, 2313, 6000, 100, '100 explosion rune')
shopModule:addBuyableItem({'manarune'}, 2298, 10000, 50, '50 manarune')


shopModule:addBuyableItem({'wand of vortex', 'vortex'}, 2190, 500, 'wand of vortex')
shopModule:addBuyableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 1000, 'wand of dragonbreath')
shopModule:addBuyableItem({'wand of plague', 'plague'}, 2188, 5000, 'wand of plague')
shopModule:addBuyableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 10000, 'wand of cosmic energy')
shopModule:addBuyableItem({'wand of inferno', 'inferno'}, 2187, 15000, 'wand of inferno')

shopModule:addBuyableItem({'snakebite rod', 'snakebite'}, 2182, 500, 'snakebite rod')
shopModule:addBuyableItem({'moonlight rod', 'moonlight'}, 2186, 1000, 'moonlight rod')
shopModule:addBuyableItem({'volcanic rod', 'volcanic'}, 2185, 5000, 'volcanic rod')
shopModule:addBuyableItem({'quagmire rod', 'quagmire'}, 2181, 10000, 'quagmire rod')
shopModule:addBuyableItem({'tempest rod', 'tempest'}, 2183, 15000, 'tempest rod')

shopModule:addSellableItem({'wand of vortex', 'vortex'}, 2190, 250, 'wand of vortex')
shopModule:addSellableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 500, 'wand of dragonbreath')
shopModule:addSellableItem({'wand of decay', 'decay'}, 2188, 2500, 'wand of decay')
shopModule:addSellableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 5000, 'wand of cosmic energy')
shopModule:addSellableItem({'wand of inferno', 'inferno'},2187, 7500, 'wand of inferno')

shopModule:addSellableItem({'snakebite rod', 'snakebite'}, 2182, 250,'snakebite rod')
shopModule:addSellableItem({'moonlight rod', 'moonlight'}, 2186, 500, 'moonlight rod')
shopModule:addSellableItem({'volcanic rod', 'volcanic'}, 2185, 2500, 'volcanic rod')
shopModule:addSellableItem({'northwind rod', 'northwind'}, 8911, 3750, 'northwind rod')
shopModule:addSellableItem({'quagmire rod', 'quagmire'}, 2181, 5000, 'quagmire rod')
shopModule:addSellableItem({'tempest rod', 'tempest'}, 2183, 7500, 'tempest rod')

npcHandler:addModule(FocusModule:new())
Here you have my runes.lua, but I think the problem is in npcsystem or modules :p
 
Last edited:
Code:
local ItemId,Money,Charges
if (getCount(msg) > 0) and (msgcontains(msg:lower(),'sd')) then
  Charges = getCount(msg)
  ItemId = 2263
  Money = 300
  talkState[talkUser] = 1
  npcHandler:say('Do you want to buy '..Charges..' '..getItemNameById(ItemId)..'s for '..Money*Charges..' gold?')
 elseif (msgcontains(msg:lower(),'yes')) and talkState[talkUser] == 1 then
   if (doPlayerRemoveMoney(cid,Money*Charges) == 1) then
      doPlayerAddItem(cid,ItemId,Charges)
      npcHandler:say('Thank you. Here you are.')
   end
end
 
Code:
local keywordHandler = KeywordHandler:new()
 local npcHandler = NpcHandler:new(keywordHandler)
 NpcSystem.parseParameters(npcHandler)
 local talkState = {}

 function onCreatureAppear(cid) npcHandlernCreatureAppear(cid) end
 function onCreatureDisappear(cid) npcHandlernCreatureDisappear(cid) end
 function onCreatureSay(cid, type, msg) npcHandlernCreatureSay(cid, type, msg) end
 function onThink() npcHandlernThink() end

function SayCallback (cid, type, msg)
local ItemId,Money,Charges
if (getCount(msg) > 0) and (msgcontains(msg:lower(),'sd')) then
  Charges = getCount(msg)
  ItemId = 2263
  Money = 300
  talkState[talkUser] = 1
  npcHandler:say('Do you want to buy '..Charges..' '..getItemNameById(ItemId)..'s for '..Money*Charges..' gold?')
 elseif (msgcontains(msg:lower(),'yes')) and talkState[talkUser] == 1 then
   if (doPlayerRemoveMoney(cid,Money*Charges) == 1) then
      doPlayerAddItem(cid,ItemId,Charges)
      npcHandler:say('Thank you. Here you are.')
   end
end
return 1
end

npcHandler:addModule(FocusModule:new())
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, SayCallback)
 
Either I have pasted it wrong or it doesn't work. Tell me exactly where to put it.
@Ok, pasted it. When I'm saying 'sd' to npc then in console appears:
[05/06/2011 11:46:54] Lua Script Error: [Npc interface]
[05/06/2011 11:46:54] data/npc/scripts/runes.lua:onCreatureSay

[05/06/2011 11:46:54] data/npc/scripts/runes.lua:18: table index is nil
[05/06/2011 11:46:54] stack traceback:
[05/06/2011 11:46:54] data/npc/scripts/runes.lua:18: in function 'callback'
[05/06/2011 11:46:54] ./data/npc/lib/npcsystem/npchandler.lua:299: in function 'onCreatureSay'
[05/06/2011 11:46:54] data/npc/scripts/runes.lua:8: in function <data/npc/scripts/runes.lua:8>
 
Last edited:
Ah yes, there isn't sd cuz I was editing it myself and some days ago I probably deleted it :P
But it's the same thing with uhs, gfbs and etc.
Tell me how to do it properly
 
Didn't help. Now when I try to buy 1 gfb it asks 'Do you want to buy 1 100 great fireball rune..', and if I want to buy 100 then it sells me 100 runes with 1 charge.
Maybe its possible to sell them in the same way as e.g. ammunition is being sold (buy 5 arrows - buy 5 sds)
 
It's npc system from tfs 0.3.0 (for tibia 7.6), I haven't changed anything.

Here you have my npchandler.lua
Code:
-- This file is part of Jiddo's advanced NpcSystem v3.0x. This npcsystem is free to use by anyone, for any purpuse. 
-- Initial release date: 2007-02-21
-- Credits: Jiddo, honux(I'm using a modified version of his Find function).
-- Please include full credits whereever you use this system, or parts of it.
-- For support, questions and updates, please consult the following thread:
-- http://otfans.net/showthread.php?t=67810

if(NpcHandler == nil) then
	
	-- Constant talkdelay behaviors.
	TALKDELAY_NONE = 0 -- No talkdelay. Npc will reply immedeatly.
	TALKDELAY_ONTHINK = 1 -- Talkdelay handled through the onThink callback function. (Default)
	TALKDELAY_EVENT = 2 -- Not yet implemented
	
	-- Currently applied talkdelay behavior. TALKDELAY_ONTHINK is default.
	NPCHANDLER_TALKDELAY = TALKDELAY_ONTHINK
	
	
	
	-- Constant indexes for defining default messages.
	MESSAGE_GREET 		= 1 -- When the player greets the npc.
	MESSAGE_FAREWELL 	= 2 -- When the player unGreets the npc.
	MESSAGE_BUY 		= 3 -- When the npc asks the player if he wants to buy something.
	MESSAGE_SELL 		= 4 -- When the npc asks the player if he wants to sell something.
	MESSAGE_ONBUY 		= 5 -- When the player successfully buys something
	MESSAGE_ONSELL 		= 6 -- When the player successfully sells something
	MESSAGE_NEEDMOREMONEY = 7 -- When the player does not have enough money
	MESSAGE_NOTHAVEITEM = 8 -- When the player is trying to sell an item he does not have.
	MESSAGE_IDLETIMEOUT = 9 -- When the player has been idle for longer then idleTime allows.
	MESSAGE_WALKAWAY 	= 10 -- When the player walks out of the talkRadius of the npc.
	MESSAGE_ALREADYFOCUSED = 11 -- When the player already has the focus of this nopc.
	MESSAGE_PLACEDINQUEUE = 12 -- When the player has been placed in the costumer queue. 
	MESSAGE_DECLINE 	= 13 -- When the player sais no to something.
	
	-- Constant indexes for callback functions. These are also used for module callback ids.
	CALLBACK_CREATURE_APPEAR 	= 1
	CALLBACK_CREATURE_DISAPPEAR = 2
	CALLBACK_CREATURE_SAY 		= 3
	CALLBACK_ONTHINK 			= 4
	CALLBACK_GREET 				= 5
	CALLBACK_FAREWELL 			= 6
	CALLBACK_MESSAGE_DEFAULT 	= 7
	
	-- Addidional module callback ids
	CALLBACK_MODULE_INIT		= 10
	CALLBACK_MODULE_RESET		= 11
	
	
	-- Constant strings defining the keywords to replace in the default messages.
	TAG_PLAYERNAME = '|PLAYERNAME|'
	TAG_ITEMCOUNT = '|ITEMCOUNT|'
	TAG_TOTALCOST = '|TOTALCOST|'
	TAG_ITEMNAME = '|ITEMNAME|'
	TAG_QUEUESIZE = '|QUEUESIZE|'
	
	
	NpcHandler = {
		keywordHandler = nil,
		queue = nil,
		focus = 0,
		talkStart = 0,
		idleTime = 30,
		talkRadius = 5,
		talkDelayTime = 1, -- Seconds to delay outgoing messages.
		talkDelay = nil,
		callbackFunctions = nil,
		modules = nil,
		messages = {
				-- These are the default replies of all npcs. They can/should be changed individually for each npc.
			[MESSAGE_GREET] 		= 'Welcome, |PLAYERNAME|! I have been expecting you.',
			[MESSAGE_FAREWELL] 		= 'Good bye, |PLAYERNAME|!',
			[MESSAGE_BUY] 			= 'Do you want to buy |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?',
			[MESSAGE_SELL] 			= 'Do you want to sell |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?',
			[MESSAGE_ONBUY] 		= 'It was a pleasure doing business with you.',
			[MESSAGE_ONSELL] 		= 'Thank you for this item, |PLAYERNAME|.',
			[MESSAGE_NEEDMOREMONEY] = 'You do not have enough money.',
			[MESSAGE_NOTHAVEITEM] 	= 'You don\'t even have that item!',
			[MESSAGE_IDLETIMEOUT] 	= 'Next please!',
			[MESSAGE_WALKAWAY] 		= 'How rude!',
			[MESSAGE_ALREADYFOCUSED]= '|PLAYERNAME|, I am already talking to you.',
			[MESSAGE_PLACEDINQUEUE] = '|PLAYERNAME|, please wait for your turn. There are |QUEUESIZE| customers before you.',
			[MESSAGE_DECLINE]		= 'Not good enough, is it?'
		}
	}
	
	
	-- Creates a new NpcHandler with an empty callbackFunction stack. 
	function NpcHandler:new(keywordHandler)
		local obj = {}
		obj.callbackFunctions = {}
		obj.modules = {}
		obj.talkDelay = {
				message = nil,
				time = nil
			}
		obj.queue = Queue:new(obj)
		obj.keywordHandler = keywordHandler
		obj.messages = {}
		setmetatable(obj.messages, self.messages)
		self.messages.__index = self.messages
		
		setmetatable(obj, self)
		self.__index = self
		return obj
	end
	
	-- Re-defines the maximum idle time allowed for a player when talking to this npc.
	function NpcHandler:setMaxIdleTime(newTime)
		self.idleTime = newTime
	end
	
	-- Attaches a new costumer queue to this npchandler.
	function NpcHandler:setQueue(newQueue)
		self.queue = newQueue
		self.queue:setHandler(self)
	end
	
	-- Attackes a new keyword handler to this npchandler
	function NpcHandler:setKeywordHandler(newHandler)
		self.keywordHandler = newHandler
	end
	
	-- Function used to change the focus of this npc. 
	function NpcHandler:changeFocus(newFocus)
		self.focus = newFocus
		self:updateFocus()
	end
	
	-- This function should be called on each onThink and makes sure the npc faces the player it is talking to.
	--	Should also be called whenever a new player is focused.
	function NpcHandler:updateFocus()
		doNpcSetCreatureFocus(self.focus)
	end
	
	-- Used when the npc should un-focus the player. 
	function NpcHandler:releaseFocus()
		self:changeFocus(0)
	end
	
	-- Returns the callback function with the specified id or nil if no such callback function exists.
	function NpcHandler:getCallback(id)
		local ret = nil
		if(self.callbackFunctions ~= nil) then
			ret = self.callbackFunctions[id]
		end
		return ret
	end
	
	-- Changes the callback function for the given id to callback.
	function NpcHandler:setCallback(id, callback)
		if(self.callbackFunctions ~= nil) then
			self.callbackFunctions[id] = callback
		end
	end
	
	-- Adds a module to this npchandler and inits it.
	function NpcHandler:addModule(module)
		if(self.modules ~= nil) then
			table.insert(self.modules, module)
			module:init(self)
		end
	end
	
	-- Calls the callback function represented by id for all modules added to this npchandler with the given arguments.
	function NpcHandler:processModuleCallback(id, ...)
		local ret = true
		for i, module in pairs(self.modules) do
			local tmpRet = true
			if(id == CALLBACK_CREATURE_APPEAR and module.callbackOnCreatureAppear ~= nil) then
				tmpRet = module:callbackCreatureAppear(unpack(arg))
				
			elseif(id == CALLBACK_CREATURE_DISAPPEAR and module.callbackOnCreatureDisappear ~= nil) then
				tmpRet = module:callbackCreatureDisappear(unpack(arg))
				
			elseif(id == CALLBACK_CREATURE_SAY and module.callbackOnCreatureSay ~= nil) then
				tmpRet = module:callbackCreatureSay(unpack(arg))
				
			elseif(id == CALLBACK_ONTHINK and module.callbackOnThink ~= nil) then
				tmpRet = module:callbackOnThink(unpack(arg))
				
			elseif(id == CALLBACK_GREET and module.callbackOnGreet ~= nil) then
				tmpRet = module:callbackOnGreet(unpack(arg))
				
			elseif(id == CALLBACK_FAREWELL and module.callbackOnFarewell ~= nil) then
				tmpRet = module:callbackOnFarewell(unpack(arg))
				
			elseif(id == CALLBACK_MESSAGE_DEFAULT and module.callbackOnMessageDefault ~= nil) then
				tmpRet = module:callbackOnMessageDefault(unpack(arg))
				
			elseif(id == CALLBACK_MODULE_RESET and module.callbackOnModuleReset ~= nil) then
				tmpRet = module:callbackOnModuleReset(unpack(arg))
			end
			if(not tmpRet) then
				ret = false
				break
			end
		end
		return ret
	end
	
	-- Returns the message represented by id.
	function NpcHandler:getMessage(id)
		local ret = nil
		if(self.messages ~= nil) then
			ret = self.messages[id]
		end
		return ret
	end
	
	-- Changes the default response message with the specified id to newMessage.
	function NpcHandler:setMessage(id, newMessage)
		if(self.messages ~= nil) then
			self.messages[id] = newMessage
		end
	end
	
	-- Translates all message tags found in msg using parseInfo
	function NpcHandler:parseMessage(msg, parseInfo)
		local ret = msg
		for search, replace in pairs(parseInfo) do
			ret = string.gsub(ret, search, replace)
		end
		return ret
	end
	
	-- Makes sure the npc un-focuses the furrently focused player, and greets the next player in the queue is it is not empty.
	function NpcHandler:unGreet()
		if(self.focus == 0) then
			return
		end
		local callback = self:getCallback(CALLBACK_FAREWELL)
		if(callback == nil or callback()) then
			if(self:processModuleCallback(CALLBACK_FAREWELL)) then
				if(self.queue == nil or not self.queue:greetNext()) then
					local msg = self:getMessage(MESSAGE_FAREWELL)
					local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(self.focus) }
					msg = self:parseMessage(msg, parseInfo)
					self:say(msg)
					self:releaseFocus()
				end
			end
		end
	end
	
	-- Greets a new player. 
	function NpcHandler:greet(cid)
		if(cid ~= 0) then
			local callback = self:getCallback(CALLBACK_GREET)
			if(callback == nil or callback(cid)) then
				if(self:processModuleCallback(CALLBACK_GREET, cid)) then
					local msg = self:getMessage(MESSAGE_GREET)
					local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
					msg = self:parseMessage(msg, parseInfo)
					self:say(msg)
				else
					return
				end
			else
				return
			end
		end
		self:changeFocus(cid)
	end
	
	-- Handles onCreatureAppear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_APPEAR callback.
	function NpcHandler:onCreatureAppear(cid)
		local callback = self:getCallback(CALLBACK_CREATURE_APPEAR)
		if(callback == nil or callback(cid)) then
			if(self:processModuleCallback(CALLBACK_CREATURE_APPEAR, cid)) then
				
			end
		end
	end
	
	-- Handles onCreatureDisappear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_DISAPPEAR callback.
	function NpcHandler:onCreatureDisappear(cid)
		local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR)
		if(callback == nil or callback(cid)) then
			if(self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid)) then
				if(self.focus == cid) then
					self:unGreet()
				end
			end
		end
	end
	
	-- Handles onCreatureSay events. If you with to handle this yourself, please use the CALLBACK_CREATURE_SAY callback.
	function NpcHandler:onCreatureSay(cid, msgtype, msg)
		local callback = self:getCallback(CALLBACK_CREATURE_SAY)
		if(callback == nil or callback(cid, msgtype, msg)) then
			if(self:processModuleCallback(CALLBACK_CREATURE_SAY, cid, msgtype, msg)) then
				if(not self:isInRange(cid)) then
					return
				end
				if(self.keywordHandler ~= nil) then
					local ret = self.keywordHandler:processMessage(cid, msg)
					if(not ret) then
						local callback = self:getCallback(CALLBACK_MESSAGE_DEFAULT)
						if(callback ~= nil and callback(cid, msgtype, msg)) then
							self.talkStart = os.time()
						end
					else
						self.talkStart = os.time()
					end
				end
			end
		end
	end
	
	-- Handles onThink events. If you with to handle this yourself, please use the CALLBACK_ONTHINK callback.
	function NpcHandler:onThink()
		local callback = self:getCallback(CALLBACK_ONTHINK)
		if(callback == nil or callback()) then
			
			if(NPCHANDLER_TALKDELAY == TALKDELAY_ONTHINK and self.talkDelay.time ~= nil and self.talkDelay.message ~= nil and os.time() >= self.talkDelay.time) then
				selfSay(self.talkDelay.message)
				self.talkDelay.time = nil
				self.talkDelay.message = nil
			end
			
			if(self:processModuleCallback(CALLBACK_ONTHINK)) then
				if(self.focus ~= 0) then
					if(not self:isInRange(self.focus)) then
						self:onWalkAway(self.focus)
					elseif(os.time()-self.talkStart > self.idleTime) then
						self:unGreet()
					else
						self:updateFocus()
					end
				end
			end
		end
	end
	
	-- Tries to greet the player iwth the given cid. This function does not override queue order, current focus etc.
	function NpcHandler:onGreet(cid)
		if(self:isInRange(cid)) then
			if(self.focus == 0) then
				self:greet(cid)
			elseif(cid == self.focus) then
				local msg = self:getMessage(MESSAGE_ALREADYFOCUSED)
				local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
				msg = self:parseMessage(msg, parseInfo)
				self:say(msg)
			else
				if(not self.queue:isInQueue(cid)) then
					self.queue:push(cid)
				end
				local msg = self:getMessage(MESSAGE_PLACEDINQUEUE)
				local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_QUEUESIZE] = self.queue:getSize() }
				msg = self:parseMessage(msg, parseInfo)
				self:say(msg)
			end
		end
	end
	
	-- Simply calls the underlying unGreet function. 
	function NpcHandler:onFarewell()
		self:unGreet()
	end
	
	-- Should be called on this npc's focus if the distance to focus is greater then talkRadius.
	function NpcHandler:onWalkAway(cid)
		if(cid == self.focus) then
			local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR)
			if(callback == nil or callback()) then
				if(self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid)) then
					if(self.queue == nil or not self.queue:greetNext()) then
						local msg = self:getMessage(MESSAGE_WALKAWAY)
						local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(self.focus) }
						msg = self:parseMessage(msg, parseInfo)
						self:say(msg)
						self:releaseFocus()
					end
				end
			end
		end
	end
	
	-- Returns true if cid is within the talkRadius of this npc.
	function NpcHandler:isInRange(cid)
		local playerPos = getPlayerPosition(cid)
		if playerPos == LUA_ERROR or playerPos == LUA_NO_ERROR then
			return false
		end
		
		local sx, sy, sz = selfGetPosition()
		local dx = math.abs(sx-playerPos.x)
		local dy = math.abs(sy-playerPos.y)
		local dz = math.abs(sz-playerPos.z)
		
		local dist = (dx^2 + dy^2)^0.5
		
		return (dist <= self.talkRadius and dz == 0)
	end
	
	-- Resets the npc into it's initial state (in regard of the keyrodhandler). 
	--	All modules are also receiving a reset call through their callbackOnModuleReset function.
	function NpcHandler:resetNpc()
		if(self:processModuleCallback(CALLBACK_MODULE_RESET)) then
			self.keywordHandler:reset()
		end
	end
	
	
	-- Makes the npc represented by this instance of NpcHandler say something. 
	--	This implements the currently set type of talkdelay.
	--	shallDelay is a boolean value. If it is false, the message is not delayed. Default value is true.
	function NpcHandler:say(message, shallDelay)
		if(shallDelay == nil) then
			shallDelay = true
		end
		if(NPCHANDLER_TALKDELAY == TALKDELAY_NONE or shallDelay == false) then
			selfSay(message)
			return
		end
		self.talkDelay.message = message
		self.talkDelay.time = os.time()+self.talkDelayTime
	end
	
	
end
 
Ahh okay :P
Here you go
Code:
-- Include external classes.
dofile(getDataDir() .. 'npc/lib/npcsystem/npcsystem.lua')

-- Callback for isPremium(cid) so Jiddo's npcsystem works
isPlayerPremiumCallback = isFree

-- move to a creature
function moveToCreature(id)
	if(isCreature(id) == FALSE) then
		debugPrint('moveToCreature(): creature not found.')
		return LUA_ERROR
	end

	local pos = getCreaturePosition(id)
	selfMoveTo(pos.x, pos.y, pos.z)
	return LUA_NO_ERROR
end

-- do one step to reach position
function moveToPosition(x,y,z)
	selfMoveTo(x, y, z)
end


-- stop talking
function selfGotoIdle()
		following = false
		attacking = false
		selfAttackCreature(0)
		target = 0
end

function getCount(msg)
	b, e = string.find(msg, "%d+")
	
	if b == nil or e == nil then
		count = 1
	else
		count = tonumber(string.sub(msg, b, e))
	end
	
	if count > 2000 then
		count = 2000
	end
	
	return count
end

-- buy an item
function buy(cid, itemid, count, cost)
	cost = count*cost
	amount = count
	if doPlayerRemoveMoney(cid, cost) == 1 then
		if getItemStackable(itemid) then
			while count > 100 do
				doPlayerAddItem(cid, itemid, 100)
				count = count - 100
			end
			
			doPlayerAddItem(cid, itemid, count) -- add the last items, if there is left
		else
			while count > 0 do
				doPlayerAddItem(cid, itemid, 1)
				count = count - 1
			end
		end
		
		if amount <= 1 then
			selfSay('Here is your '.. getItemName(itemid) .. '!')
		else
			selfSay('Here are your '.. amount ..' '.. getItemName(itemid) .. 's!')		
		end
	else
		selfSay('Sorry, you do not have enough money.')
	end
end

function buyFluidContainer(cid, itemid, count, cost, fluidtype)
	cost = count*cost
	amount = count
	if doPlayerRemoveMoney(cid, cost) == 1 then
		while count > 0 do
			doPlayerAddItem(cid, itemid, fluidtype)
			count = count - 1
		end
		
		if amount <= 1 then
			selfSay('Here is your '.. getItemName(itemid) .. '!')
		else
			selfSay('Here are your '.. amount ..' '.. getItemName(itemid) .. 's!')		
		end
	else
		selfSay('Sorry, you do not have enough money.')
	end
end

-- sell an item
function sell(cid, itemid, count, cost)
	cost = count*cost
	if doPlayerRemoveItem(cid, itemid, count) == 1 then
		coins = math.floor(cost/10000)
		crystals = coins
		while coins > 100 do
			doPlayerAddItem(cid, 2160, 100)
			coins = coins - 100
		end
		
		doPlayerAddItem(cid, 2160, coins)
		cost = cost - crystals*10000
		
		coins = math.floor(cost/100)
		if coins > 0 then
			doPlayerAddItem(cid, 2152, coins)
			cost = cost - coins*100
		end
		coins = cost
		if cost > 0 and cost < 100 then
			doPlayerAddItem(cid, 2148, coins)
			cost = cost - coins
		end
		
		if cost > 0 then
			selfSay('You couldn\'t retrieve '.. cost ..' gold pieces, please contact the admin.')
		end
		
		if count <= 1 then
			selfSay('Thanks for this '.. getItemName(itemid) .. '!')
		else
			selfSay('Thanks for these '.. count..' '.. getItemName(itemid) .. 's!')		
		end
	else
		selfSay('Sorry, you do not have this item.')
	end
end

-- pay for anything?
function pay(cid, cost)
	if doPlayerRemoveMoney(cid, cost) == 1 then
		return true
	else
		return false
	end
end


-- Travel player
function travel(cid, x, y, z)
	destpos = {x = x, y = y, z = z}
	doTeleportThing(cid, destpos)
	doSendMagicEffect(destpos, 10)
end

function msgcontains(txt, str)
	return (string.find(txt, str) and not string.find(txt, '(%w+)' .. str) and not string.find(txt, str .. '(%w+)'))
end
 
Maybe its possible to sell them in the same way as e.g. ammunition is being sold (buy 5 arrows - buy 5 sds)
it's not, because number of charges per rune isn't accessible by the buy function (more npcsystem files have to be edited)

post modules.lua
 
Code:
-- This file is part of Jiddo's advanced NpcSystem v3.0x. This npcsystem is free to use by anyone, for any purpuse. 
-- Initial release date: 2007-02-21
-- Credits: Jiddo, honux(I'm using a modified version of his Find function).
-- Please include full credits whereever you use this system, or parts of it.
-- For support, questions and updates, please consult the following thread:
-- http://otfans.net/showthread.php?t=67810

if(Modules == nil) then
	
	-- default words for greeting and ungreeting the npc. Should be a talbe containing all such words.
	FOCUS_GREETWORDS = {'hi', 'hello'}
	FOCUS_FAREWELLWORDS = {'bye', 'farewell', 'cya'}
	
	-- The word for accepting/declining an offer. CAN ONLY CONTAIN ONE FIELD! Should be a teble with a single string value.
	SHOP_YESWORD = {'yes'}
	SHOP_NOWORD = {'no'}
	
	-- Pattern used to get the amount of an item a player wants to buy/sell.
	PATTERN_COUNT = '%d+'
	
	
	-- Constants used to separate buying from selling.
	SHOPMODULE_SELL_ITEM 	= 1
	SHOPMODULE_BUY_ITEM 	= 2
	
	
	Modules = {
			parseableModules = {}
		}
	
	
	StdModule = {
		
		}
	
	-- These callback function must be called with parameters.npcHandler = npcHandler in the parameters table or they will not work correctly.
	-- Notice: The members of StdModule have not yet been tested. If you find any bugs, please report them to me.
	
	-- Usage:
		-- keywordHandler:addKeyword({'offer'}, StdModule.say, {npcHandler = npcHandler, text = 'I sell many powerful melee weapons.'})
	function StdModule.say(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.say called without any npcHandler instance.')
		end
		if(cid ~= npcHandler.focus and (parameters.onlyFocus == nil or parameters.onlyFocus == true)) then
			return false
		end
		local parseInfo = {
				[TAG_PLAYERNAME] = getPlayerName(cid),
			}
		msgout = npcHandler:parseMessage(parameters.text or parameters.message, parseInfo)
		npcHandler:say(msgout)
		if(parameters.reset == true) then
			npcHandler:resetNpc()
		elseif(parameters.moveup ~= nil and type(parameters.moveup) == 'number') then
			npcHandler.keywordHandler:moveUp(parameters.moveup)
		end
		return true
	end

		-- local node1 = keywordHandler:addKeyword({'promot'}, StdModule.say, {npcHandler = npcHandler, text = 'I can promote you for 20000 gold coins. Do you want me to promote you?'})
		-- 		node1:addChildKeyword({'yes'}, StdModule.promotePlayer, {npcHandler = npcHandler, cost = 10000, level = 20}, text = 'Congratulations! You are now promoted.')
		-- 		node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'Allright then. Come back when you are ready.'}, reset = true)
	function StdModule.promotePlayer(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.promotePlayer called without any npcHandler instance.')
		end
		if(cid ~= npcHandler.focus) then
			return false
		end
 
		if(isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium == false) then
				if getPlayerVocation(cid) == 5 then
				npcHandler:say('You are already promoted!', cid)
			elseif getPlayerVocation(cid) == 6 then
				npcHandler:say('You are already promoted!', cid)
			elseif getPlayerVocation(cid) == 7 then
				npcHandler:say('You are already promoted!', cid)
			elseif getPlayerVocation(cid) == 8 then
				npcHandler:say('You are already promoted!', cid)
			elseif(getPlayerLevel(cid) < parameters.level) then
				npcHandler:say('I am sorry, but I can only promote you once you have reached level ' .. parameters.level .. '.', cid)
			elseif(doPlayerRemoveMoney(cid, parameters.cost) ~= TRUE) then
				npcHandler:say('You do not have enough money!', cid)
		elseif
 
				getPlayerVocation(cid) == 1 then
				doPlayerSetVocation(cid, 5)
                                doPlayerRemoveMoney(cid, parameters.cost)
elseif
				getPlayerVocation(cid) == 2 then
				doPlayerSetVocation(cid, 6)
				doPlayerRemoveMoney(cid, parameters.cost)
 
 
elseif
				getPlayerVocation(cid) == 3 then
				doPlayerSetVocation(cid, 7)
				doPlayerRemoveMoney(cid, parameters.cost)
elseif
				getPlayerVocation(cid) == 4 then
				doPlayerSetVocation(cid, 8)
				doPlayerRemoveMoney(cid, parameters.cost)
			end
 
 
				npcHandler:say(parameters.text, cid)
 
 
 
 
		end
		npcHandler:resetNpc()
		return true
 
 
	end

	function StdModule.learnSpell(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.buySpell called without any npcHandler instance.')
		end
		if(cid ~= npcHandler.focus) then
			return false
		end

		if(isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium == false) then
			if getPlayerLearnedInstantSpell(cid, parameters.spellName) == TRUE then
				npcHandler:say('You already know this spell.', cid)
			elseif getPlayerLevel(cid) < parameters.level then
				npcHandler:say('You need to obtain a level of ' .. parameters.level .. ' or higher to be able to learn ' .. parameters.spellName .. '.', cid)
			elseif getPlayerVocation(cid) ~= parameters.vocation and getPlayerVocation(cid) ~= parameters.vocation + 4 and vocation ~= 9 then
				npcHandler:say('This spell is not for your vocation', cid)
			elseif doPlayerRemoveMoney(cid, parameters.price) == FALSE then
				npcHandler:say('You do not have enough money, this spell costs ' .. parameters.price .. ' gold.', cid)
			else
				npcHandler:say('You have learned ' .. parameters.spellName .. '.', cid)
				playerLearnInstantSpell(cid, parameters.spellName)
			end
		else
			npcHandler:say('You need a premium account in order to buy ' .. parameters.spellName .. '.', cid)
		end
		npcHandler:resetNpc()
		return true
	end

	function StdModule.bless(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.bless called without any npcHandler instance.')
		end

		if(cid ~= npcHandler.focus) then
			return false
		end

		if(isPremium(cid) or isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium == false) then
			if getPlayerBlessing(cid, parameters.bless) then
				npcHandler:say("Gods have already blessed you with this blessing!", cid)
			elseif doPlayerRemoveMoney(cid, parameters.cost) == FALSE then
				npcHandler:say("You don't have enough money for blessing.", cid)
			else
				npcHandler:say("You have been blessed by one of the five gods!", cid)
				doPlayerAddBlessing(cid, parameters.bless)
			end
		else
			npcHandler:say('You need a premium account in order to be blessed.', cid)
		end

		npcHandler:resetNpc()
		return true
	end
	
	
	function StdModule.travel(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.travel called without any npcHandler instance.')
		end
		if(cid ~= npcHandler.focus) then
			return false
		end
		
		if(isPremium(cid) or isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium == false) then
			if(parameters.level ~= nil and getPlayerLevel(cid) < parameters.level) then
				npcHandler:say('You must reach level ' .. parameters.level .. ' before I can let you go there.')
			elseif(doPlayerRemoveMoney(cid, parameters.cost) ~= TRUE) then
				npcHandler:say('You do not have enough money!')
			else
				doTeleportThing(cid, parameters.destination)
				doSendMagicEffect(parameters.destination, 10)
			end
		else
			npcHandler:say('I can only allow premium players to travel with me.')
		end
		
		npcHandler:resetNpc()
		return true
	end
	

	function StdModule.bless(cid, message, keywords, parameters, node)
		local npcHandler = parameters.npcHandler
		if(npcHandler == nil) then
			error('StdModule.bless called without any npcHandler instance.')
		end

		if(cid ~= npcHandler.focus) then
			return false
		end

		if(isPremium(cid) or isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium == false) then
			if getPlayerBlessing(cid, parameters.bless) then
				npcHandler:say("Gods have already blessed you with this blessing!", cid)
			elseif doPlayerRemoveMoney(cid, parameters.cost) == FALSE then
				npcHandler:say("You don't have enough money for blessing.", cid)
			else
				npcHandler:say("You have been blessed by one of the five gods!", cid)
				doPlayerAddBlessing(cid, parameters.bless)
			end
		else
			npcHandler:say('You need a premium account in order to be blessed.', cid)
		end

		npcHandler:resetNpc()
		return true
	end
	
	
	FocusModule = {
			npcHandler = nil
		}
	
	-- Creates a new instance of FocusModule without an associated NpcHandler.
	function FocusModule:new()
		local obj = {}
		setmetatable(obj, self)
		self.__index = self
		return obj
	end
	
	-- Inits the module and associates handler to it.
	function FocusModule:init(handler)
		self.npcHandler = handler
		for i, word in pairs(FOCUS_GREETWORDS) do
			local obj = {}
			table.insert(obj, word)
			obj.callback = FOCUS_GREETWORDS.callback or FocusModule.messageMatcher
			handler.keywordHandler:addKeyword(obj, FocusModule.onGreet, {module = self})
		end
		
		for i, word in pairs(FOCUS_FAREWELLWORDS) do
			local obj = {}
			table.insert(obj, word)
			obj.callback = FOCUS_FAREWELLWORDS.callback or FocusModule.messageMatcher
			handler.keywordHandler:addKeyword(obj, FocusModule.onFarewell, {module = self})
		end
		
		return true
	end
	
	
	-- Greeting callback function.
	function FocusModule.onGreet(cid, message, keywords, parameters)
		parameters.module.npcHandler:onGreet(cid)
		return true
	end
	
	-- UnGreeting callback function.
	function FocusModule.onFarewell(cid, message, keywords, parameters)
		if(parameters.module.npcHandler.focus == cid) then
			parameters.module.npcHandler:onFarewell()
			return true
		else
			return false
		end
	end
	
	-- Custom message matching callback function for greeting messages.
	function FocusModule.messageMatcher(keywords, message)
		for i, word in pairs(keywords) do
			if(type(word) == 'string') then
				if string.find(message, word) and not string.find(message, '[%w+]' .. word) and not string.find(message, word .. '[%w+]') then
	        		return true
	    		end
	    	end
    	end
    	return false
	end
	
	
	
	KeywordModule = {
		npcHandler = nil
	}
	-- Add it to the parseable module list.
	Modules.parseableModules['module_keywords'] = KeywordModule
	
	function KeywordModule:new()
		local obj = {}
		setmetatable(obj, self)
		self.__index = self
		return obj
	end
	
	function KeywordModule:init(handler)
		self.npcHandler = handler
		return true
	end
	
	-- Parses all known parameters.
	function KeywordModule:parseParameters()
		local ret = NpcSystem.getParameter('keywords')
		if(ret ~= nil) then
			self:parseKeywords(ret)
		end
	end
	
	function KeywordModule:parseKeywords(data)
		local n = 1
		for keys in string.gmatch(data, '[^;]+') do
			local i = 1
			
			local keywords = {}
			
			for temp in string.gmatch(keys, '[^,]+') do
				table.insert(keywords, temp)
				i = i+1
			end
			
			if(i ~= 1) then
				local reply = NpcSystem.getParameter('keyword_reply' .. n)
				if(reply ~= nil) then
					self:addKeyword(keywords, reply)
				else
					print('[Warning] NpcSystem:', 'Parameter \'' .. 'keyword_reply' .. n .. '\' missing. Skipping...')
				end
			else
				print('[Warning] NpcSystem:', 'No keywords found for keyword set #' .. n .. '. Skipping...')
			end
			n = n+1
		end
	end
	
	function KeywordModule:addKeyword(keywords, reply)
		self.npcHandler.keywordHandler:addKeyword(keywords, StdModule.say, {npcHandler = self.npcHandler, onlyFocus = true, text = reply, reset = true})
	end
	
	
	
	TravelModule = {
		npcHandler = nil,
		destinations = nil,
		yesNode = nil,
		noNode = nil,
	}
	-- Add it to the parseable module list.
	Modules.parseableModules['module_travel'] = TravelModule
	
	function TravelModule:new()
		local obj = {}
		setmetatable(obj, self)
		self.__index = self
		return obj
	end
	
	function TravelModule:init(handler)
		self.npcHandler = handler
		self.yesNode = KeywordNode:new(SHOP_YESWORD, TravelModule.onConfirm, {module = self})
		self.noNode = KeywordNode:new(SHOP_NOWORD, TravelModule.onDecline, {module = self})
		self.destinations = {}
		return true
	end
	
	-- Parses all known parameters.
	function TravelModule:parseParameters()
		local ret = NpcSystem.getParameter('travel_destinations')
		if(ret ~= nil) then
			self:parseDestinations(ret)
			
			self.npcHandler.keywordHandler:addKeyword({'destination'}, TravelModule.listDestinations, {module = self})
			self.npcHandler.keywordHandler:addKeyword({'where'}, TravelModule.listDestinations, {module = self})
			self.npcHandler.keywordHandler:addKeyword({'travel'}, TravelModule.listDestinations, {module = self})
			
		end
	end
	
	function TravelModule:parseDestinations(data)
		for destination in string.gmatch(data, '[^;]+') do
			local i = 1
			
			local name = nil
			local x = nil
			local y = nil
			local z = nil
			local cost = nil
			local premium = false
			
			
			for temp in string.gmatch(destination, '[^,]+') do
				if(i == 1) then
					name = temp
				elseif(i == 2) then
					x = tonumber(temp)
				elseif(i == 3) then
					y = tonumber(temp)
				elseif(i == 4) then
					z = tonumber(temp)
				elseif(i == 5) then
					cost = tonumber(temp)
				elseif(i == 6) then
					premium = temp == 'true'
				else
					print('[Warning] NpcSystem:', 'Unknown parameter found in travel destination parameter.', temp, destination)
				end
				i = i+1
			end
			
			if(name ~= nil and x ~= nil and y ~= nil and z ~= nil and cost ~= nil) then
				self:addDestination(name, {x=x, y=y, z=z}, cost, premium)
			else
				print('[Warning] NpcSystem:', 'Parameter(s) missing for travel destination:', name, x, y, z, cost, premium)
			end
		end
	end
	
	function TravelModule:addDestination(name, position, price, premium)
		table.insert(self.destinations, name)
		
		local parameters = {
				cost = price,
				destination = position,
				premium = premium,
				module = self
			}
		local keywords = {}
		table.insert(keywords, name)
		
		local keywords2 = {}
		table.insert(keywords2, 'bring me to ' .. name)
		local node = self.npcHandler.keywordHandler:addKeyword(keywords, TravelModule.travel, parameters)
		self.npcHandler.keywordHandler:addKeyword(keywords2, TravelModule.bringMeTo, parameters)
		node:addChildKeywordNode(self.yesNode)
		node:addChildKeywordNode(self.noNode)
	end
	
	function TravelModule.travel(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		
		local npcHandler = module.npcHandler
		
		
		local cost = parameters.cost
		local destination = parameters.destination
		local premium = parameters.premium
		
		module.npcHandler:say('Do you want to travel to ' .. keywords[1] .. ' for ' .. cost .. ' gold coins?')
		return true
		
	end
	
	function TravelModule.onConfirm(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		
		local npcHandler = module.npcHandler
		
		
		local parentParameters = node:getParent():getParameters()
		local cost = parentParameters.cost
		local destination = parentParameters.destination
		local premium = parentParameters.premium
		
		if(isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium ~= true) then
			if(doPlayerRemoveMoney(cid, cost) ~= TRUE) then
				npcHandler:say('You do not have enough money!')
			else
				npcHandler:say('It was a pleasure doing business with you.', false)
				npcHandler:releaseFocus()
				doTeleportThing(cid, destination)
				doSendMagicEffect(destination, 10)
			end
		else
			npcHandler:say('I can only allow premium players to travel there.')
		end
		
		npcHandler:resetNpc()
		return true
	end
	
	-- onDecliune keyword callback function. Generally called when the player sais 'no' after wanting to buy an item. 
	function TravelModule.onDecline(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		local parentParameters = node:getParent():getParameters()
		local parseInfo = {
				[TAG_PLAYERNAME] = getPlayerName(cid),
			}
		local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), parseInfo)
		module.npcHandler:say(msg)
		module.npcHandler:resetNpc()
		return true
	end
	
	function TravelModule.bringMeTo(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid == module.npcHandler.focus) then
			return false
		end
		
		local cost = parameters.cost
		local destination = parameters.destination
		local premium = parameters.premium
		
		if(isPlayerPremiumCallback == nil or isPlayerPremiumCallback(cid) == true or parameters.premium ~= true) then
			if(doPlayerRemoveMoney(cid, cost) == TRUE) then
				doTeleportThing(cid, destination)
				doSendMagicEffect(destination, 10)
			end
		end
		
		return true
	end
	
	function TravelModule.listDestinations(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		
		local msg = 'I can bring you to '
		--local i = 1
		local maxn = table.maxn(module.destinations)
		for i,destination in pairs(module.destinations) do
			msg = msg .. destination
			if(i == maxn-1) then
				msg = msg .. ' and '
			elseif(i == maxn) then
				msg = msg .. '.'
			else
				msg = msg .. ', '
			end
			i = i+1
		end
		
		module.npcHandler:say(msg)
		module.npcHandler:resetNpc()
		return true
	end
	
	
	
	
	ShopModule = {
		yesNode = nil,
		noNode = nil,
		npcHandler = nil,
		noText = '',
		maxCount = 500,
		amount = 0
	}
	-- Add it to the parseable module list.
	Modules.parseableModules['module_shop'] = ShopModule
	
	-- Creates a new instance of ShopModule
	function ShopModule:new()
		local obj = {}
		setmetatable(obj, self)
		self.__index = self
		return obj
	end
	
	-- Parses all known parameters.
	function ShopModule:parseParameters()
		
		local ret = NpcSystem.getParameter('shop_sellable')
		if(ret ~= nil) then
			self:parseSellable(ret)
		end
		
		local ret = NpcSystem.getParameter('shop_buyable')
		if(ret ~= nil) then
			self:parseBuyable(ret)
		end
		
	end
	
	-- Parse a string contaning a set of buyable items.
	function ShopModule:parseBuyable(data)
		for item in string.gmatch(data, '[^;]+') do
			local i = 1
			
			local name = nil
			local itemid = nil
			local cost = nil
			local charges = nil
			
			for temp in string.gmatch(item, '[^,]+') do
				if(i == 1) then
					name = temp
				elseif(i == 2) then
					itemid = tonumber(temp)
				elseif(i == 3) then
					cost = tonumber(temp)
				elseif(i == 4) then
					charges = tonumber(temp)
				else
					print('[Warning] NpcSystem:', 'Unknown parameter found in buyable items parameter.', temp, item)
				end
				i = i+1
			end
			
			if(name ~= nil and itemid ~= nil and cost ~= nil) then
				if((isItemRune(itemid) == TRUE or isItemFluidContainer(itemid) == TRUE) and charges == nil) then
					print('[Warning] NpcSystem:', 'Charges missing for parameter item:' , item)
				else
					local names = {}
					table.insert(names, name)
					self:addBuyableItem(names, itemid, cost, charges)
				end
			else
				print('[Warning] NpcSystem:', 'Parameter(s) missing for item:', name, itemid, cost)
			end
		end
	end
	
	-- Parse a string contaning a set of sellable items.
	function ShopModule:parseSellable(data)
		for item in string.gmatch(data, '[^;]+') do
			local i = 1
			
			local name = nil
			local itemid = nil
			local cost = nil
			
			for temp in string.gmatch(item, '[^,]+') do
				if(i == 1) then
					name = temp
				elseif(i == 2) then
					itemid = tonumber(temp)
				elseif(i == 3) then
					cost = tonumber(temp)
				else
					print('[Warning] NpcSystem:', 'Unknown parameter found in sellable items parameter.', temp, item)
				end
				i = i+1
			end
			
			if(name ~= nil and itemid ~= nil and cost ~= nil) then
				local names = {}
				table.insert(names, name)
				self:addSellableItem(names, itemid, cost)
			else
				print('[Warning] NpcSystem:', 'Parameter(s) missing for item:', name, itemid, cost)
			end
		end
	end
	
	-- Initializes the module and associates handler to it.
	function ShopModule:init(handler)
		self.npcHandler = handler
		self.yesNode = KeywordNode:new(SHOP_YESWORD, ShopModule.onConfirm, {module = self})
		self.noNode = KeywordNode:new(SHOP_NOWORD, ShopModule.onDecline, {module = self})
		self.noText = handler:getMessage(MESSAGE_DECLINE)
		
		return true
	end
	
	-- Resets the module-specific variables.
	function ShopModule:reset()
		self.amount = 0
	end
	
	-- Function used to match a number value from a string.
	function ShopModule:getCount(message)
		local ret = 1
		local b, e = string.find(message, PATTERN_COUNT)
		if b ~= nil and e ~= nil then
			ret = tonumber(string.sub(message, b, e))
		end
		if(ret <= 0) then
			ret = 1
		elseif(ret > self.maxCount) then
			ret = self.maxCount
		end
		
		return ret
	end
	
	-- Adds a new buyable item. 
	--	names = A table containing one or more strings of alternative names to this item.
	--	itemid = the itemid of the buyable item
	--	cost = the price of one single item with item id itemid ^^
	--	charges - The charges of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer and no realname is needed. Default value is nil.
	--	realname - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (keywords[1]/names  will be used)
	function ShopModule:addBuyableItem(names, itemid, cost, charges, realname)
		for i, name in pairs(names) do
			local parameters = {
					itemid = itemid,
					cost = cost,
					eventType = SHOPMODULE_BUY_ITEM,
					module = self
				}
			if(realname ~= nil) then
				parameters.realname = realname
			end
			if(isItemRune(itemid) == TRUE or isItemFluidContainer(itemid) == TRUE) then
				parameters.charges = charges
			end
			keywords = {}
			table.insert(keywords, name)
			local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
			node:addChildKeywordNode(self.yesNode)
			node:addChildKeywordNode(self.noNode)
		end
	end
	
	-- Adds a new sellable item. 
	--	names = A table containing one or more strings of alternative names to this item.
	--	itemid = the itemid of the buyable item
	--	cost = the price of one single item with item id itemid ^^
	--	realname - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (keywords[2]/names will be used)
	function ShopModule:addSellableItem(names, itemid, cost, realname)
		for i, name in pairs(names) do
			local parameters = {
					itemid = itemid,
					cost = cost,
					eventType = SHOPMODULE_SELL_ITEM,
					module = self
				}
			if(realname ~= nil) then
				parameters.realname = realname
			end
			keywords = {}
			table.insert(keywords, 'sell')
			table.insert(keywords, name)
			local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
			node:addChildKeywordNode(self.yesNode)
			node:addChildKeywordNode(self.noNode)
		end
	end
	
	
	-- onModuleReset callback function. Calls ShopModule:reset()
	function ShopModule:callbackOnModuleReset()
		self:reset()
		
		return true
	end
	
	
	-- tradeItem callback function. Makes the npc say the message defined by MESSAGE_BUY or MESSAGE_SELL
	function ShopModule.tradeItem(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		local count = module:getCount(message)
		module.amount = count
		local tmpName = nil
		if(parameters.eventType == SHOPMODULE_SELL_ITEM) then
			tmpName = node:getKeywords()[2]
		elseif(parameters.eventType == SHOPMODULE_BUY_ITEM) then
			tmpName = node:getKeywords()[1]
		end
		local parseInfo = {
				[TAG_PLAYERNAME] = getPlayerName(cid),
				[TAG_ITEMCOUNT] = module.amount,
				[TAG_TOTALCOST] = parameters.cost*module.amount,
				[TAG_ITEMNAME] = parameters.realname or tmpName
			}
		
		if(parameters.eventType == SHOPMODULE_SELL_ITEM) then
			local msg = module.npcHandler:getMessage(MESSAGE_SELL)
			msg = module.npcHandler:parseMessage(msg, parseInfo)
			module.npcHandler:say(msg)
		elseif(parameters.eventType == SHOPMODULE_BUY_ITEM) then
			local msg = module.npcHandler:getMessage(MESSAGE_BUY)
			msg = module.npcHandler:parseMessage(msg, parseInfo)
			module.npcHandler:say(msg)
		end
		
		return true
		
	end
	
	
	-- onConfirm keyword callback function. Sells/buys the actual item.
	function ShopModule.onConfirm(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		local parentParameters = node:getParent():getParameters()
		local parseInfo = {
				[TAG_PLAYERNAME] = getPlayerName(cid),
				[TAG_ITEMCOUNT] = module.amount,
				[TAG_TOTALCOST] = parentParameters.cost*module.amount,
				[TAG_ITEMNAME] = parentParameters.realname or node:getParent():getKeywords()[1]
			}
		
		if(parentParameters.eventType == SHOPMODULE_SELL_ITEM) then
			local ret = doPlayerSellItem(cid, parentParameters.itemid, module.amount, parentParameters.cost*module.amount)
			if(ret == LUA_NO_ERROR) then
				local msg = module.npcHandler:getMessage(MESSAGE_ONSELL)
				msg = module.npcHandler:parseMessage(msg, parseInfo)
				module.npcHandler:say(msg)
			else
				local msg = module.npcHandler:getMessage(MESSAGE_NOTHAVEITEM)
				msg = module.npcHandler:parseMessage(msg, parseInfo)
				module.npcHandler:say(msg)
			end
		elseif(parentParameters.eventType == SHOPMODULE_BUY_ITEM) then
			local ret = doPlayerBuyItem(cid, parentParameters.itemid, module.amount, parentParameters.cost*module.amount, parentParameters.charges)
			if(ret == LUA_NO_ERROR) then
				local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
				msg = module.npcHandler:parseMessage(msg, parseInfo)
				module.npcHandler:say(msg)
			else
				local msg = module.npcHandler:getMessage(MESSAGE_NEEDMOREMONEY)
				msg = module.npcHandler:parseMessage(msg, parseInfo)
				module.npcHandler:say(msg)
			end
		end
		
		module.npcHandler:resetNpc()
		return true
	end
	
	-- onDecliune keyword callback function. Generally called when the player sais 'no' after wanting to buy an item. 
	function ShopModule.onDecline(cid, message, keywords, parameters, node)
		local module = parameters.module
		if(cid ~= module.npcHandler.focus) then
			return false
		end
		local parentParameters = node:getParent():getParameters()
		local parseInfo = {
				[TAG_PLAYERNAME] = getPlayerName(cid),
				[TAG_ITEMCOUNT] = module.amount,
				[TAG_TOTALCOST] = parentParameters.cost*module.amount,
				[TAG_ITEMNAME] = parentParameters.realname or node:getParent():getKeywords()[1]
			}
		local msg = module.npcHandler:parseMessage(module.noText, parseInfo)
		module.npcHandler:say(msg)
		module.npcHandler:resetNpc()
		return true
	end
end
 
Back
Top