Today I wrote one useful function.
getBA(name)
(bank account storage id = 300)
Add this code to you NPC / npc.lua.
Old balance check code in NPC scripts:
New balance check code in NPC scripts :
It check balance of offline and online players, auto create account if player doesn't have.
RETURN:
-1 - if player with name doesn't exist on server
0 or more - cash on account
I'll try to post "setBA(name, value)" - it set back account value for offline and online players.
getBA(name)
(bank account storage id = 300)
Add this code to you NPC / npc.lua.
Code:
function getBA(name)
local cid = getPlayerByName(name)
if isPlayer(cid) == TRUE then
--player is online
local player_cash_str = getPlayerStorageValue(cid, 300)
--create bank account if not exist
if player_cash_str < 0 then
setPlayerStorageValue(cid,300,0)
player_cash = 0
else
player_cash = player_cash_str
end
else
--player is offline, load DB connection info and connect
dofile("./config.lua")
if sqlType == "mysql" then
env = assert(luasql.mysql())
con = assert(env:connect(mysqlDatabase, mysqlUser, mysqlPass, mysqlHost, mysqlPort))
else -- sqlite
env = assert(luasql.sqlite3())
con = assert(env:connect(sqliteDatabase))
end
--check is player exist
local nametodb = escapeString(name)
result_plr = assert(con:execute("SELECT `id` FROM `players` WHERE `name` = '" .. nametodb .. "';"))
player = result_plr:fetch({}, "a")
local players = 0
local guid = 0
while player do
players = players + 1
guid = tonumber(player.id)
player = result_plr:fetch (player, "a")
end
if players > 0 then
if guid > 0 then
--player exist, check his account status
storageqry = assert(con:execute("SELECT `value` FROM `player_storage` WHERE `player_id` = '" .. guid .. "' AND `key` = 300;"))
storage = storageqry:fetch({}, "a")
local whiles = 0
while storage do
whiles = whiles + 1
player_cash = tonumber(storage.value)
storage = storageqry:fetch (storage, "a")
end
if whiles < 1 then
--if player hasn't account, create account and set account balance value to 0
assert(con:execute("INSERT INTO `player_storage` (`player_id` ,`key` ,`value`) VALUES ('" .. guid .. "', '300', '0');"))
player_cash = 0
end
end
else
--player with this name doesn't exist
player_cash = -1
end
con:close()
env:close()
end
--if player not exist return -1
--if player exist return his bank account value
return player_cash
end
Code:
local balance = getPlayerStorageValue(cid, STORAGE_BANK )
if balance >= 0 then
selfSay("Your account balance is " .. tostring(balance) .. " gold.")
else
selfSay("You haven't stored anything in your account yet.")
end
Code:
local name = getPlayerName(cid)
local balance = getBA(name)
if balance > 0 then
selfSay("Your account balance is " .. tostring(balance) .. " gold.")
else
selfSay("You haven't stored anything in your account yet.")
end
RETURN:
-1 - if player with name doesn't exist on server
0 or more - cash on account
I'll try to post "setBA(name, value)" - it set back account value for offline and online players.
Last edited by a moderator: