Lua/Wow: UseInventoryItem() issue - lua

My goal is to create a script that warns when you are disenchanting a piece you don't want. When disenchanting an item straight from inventory, I could use the UseInventoryItem() API. Since UseInventoryItem() seems to work only on inventory slot right click, I created this script, based on GetMouseFocus() API, that works with the original interface of the game: but if someone used an addon, would it still work?
Of course, better solutions are welcome
local mt = {
__index = {
isvalue = function(t, value)
local is = false
for k, entry in ipairs(t) do
if (entry == value) then
is = true
break
end
end
return is
end
}
};
local protected = { "item1", "item2", "item3", "etch." }; -- items I want to protect
setmetatable(protected, mt);
local disenchanting;
local antidisenchant = CreateFrame("Frame");
antidisenchant:RegisterEvent("UNIT_SPELLCAST_SENT");
antidisenchant:SetScript("OnEvent", function(self, event, ...)
if (event == "UNIT_SPELLCAST_SENT") then
if (arg2 == "Disenchant") then
disenchanting = true
end
end
end);
antidisenchant:SetScript("OnUpdate", function()
if GetMouseFocus() then -- GetMouseFocus() returns the frame that currently has mouse focus.
local TargetItemID = GetInventoryItemID("player",GetMouseFocus():GetID()) -- The IDs of each inventory slot frame have the same id as the slot (16 for main hand, 17 for off hand etc.).
if (TargetItemID) and (string.find(GetMouseFocus():GetName(),"Slot")) then -- Inventory slot frame are named like "CharacterMainHandSlot".
local name, link = GetItemInfo(TargetItemID)
if (disenchanting) and (protected:isvalue(name)) then
DEFAULT_CHAT_FRAME:AddMessage("WARNING! YOU'RE DISENCHANTING "..link,1,0,0)
end
end
end
end)

Related

ROBLOX LUA(u) Attempt to call a nil value on Database

I'm trying to make a DB and I'm still in testing phrase, but it doesn't work.
Basically the error is, I want it so if I type: ModuleScript:GetDB("salvage").Set("key", "value"), it would return a value, but it doesn't due to an error.
Any help is highly appreciated.
Error:
Photo
Server Script:
local ModuleScript = require(game.ServerStorage.ModuleScript)
game.Players.PlayerAdded:Connect(function(p)
p.Chatted:Connect(function(msg)
if msg == "t" then
print("lol")
print(ModuleScript:GetDB("salvage"))
ModuleScript:GetDB("salvage").Set("key", "value")
end
end)
end)
Module script:
--Variables
local dss = game:GetService("DataStoreService")
-- Tables
local greenwich = {}
local dbFunctions = {}
--Functions
function greenwich:GetDB(name)
local db = dss:GetDataStore(name)
local new = {}
new.store = db
coroutine.resume(coroutine.create(function()
for k, v in ipairs(dbFunctions) do
new[k] = function(...)
local args = { ... }
v(new.store, unpack(args))
end
end
end))
print(new.store.Name, name)
return new
end
function dbFunctions:Set(store, key, value)
print(value)
return value
end
--Returning everything.
return greenwich
Thanks in advance.
ModuleScript:GetDB("salvage") returns new which does not have a field Set so you cannot call ModuleScript:GetDB("salvage").Set("key", "value)
Set is a field of dbFunctions. You run a generic for loop over it using the ipairs iterator. dbFunctions is not a seqence, hence ipairs does not work for it. Use pairs instead.

Lua Scripts disabling each other in Roblox Studio

I'm trying to make a game in Roblox (a tycoon) and, considering it's my first time making a game, I'm using some pre-made scripts and models along with youtube tutorials. My problem right now is that I have two scripts, both under the same name, DevProductHandler, (I've tried changing their names but the problem still persists) and it seems like only one will run at a time whenever I test the game. Disabling one script allows the other to run perfectly fine, and enabling both causes only one script to work, randomly picking which one will run each time.
One of the scripts is meant to control purchasing products that are prompted from a GUI, and the other controls purchases prompted from tycoon buttons that you walk on top of. I've tried merging the scripts by copy-pasting one underneath the other, but it still only makes the GUI DevProductHandler script work. I don't know if there are some overlapping variables or something that would cause one script to not allow the other to run, but I think that's most likely the issue, although I'm not sure how to go about fixing that I'm new at Lua and game creation so I was wondering if anyone could help me find out the issue. These are the scripts.
local Tycoon = script.Parent.Tycoons:GetChildren()[1]
script.Parent = game.ServerScriptService
local DevProducts = {}
local MarketplaceService = game:GetService('MarketplaceService')
for i,v in pairs(Tycoon:WaitForChild('Buttons'):GetChildren()) do
if v:FindFirstChild('DevProduct') then
if v.DevProduct.Value > 0 then
DevProducts[v.DevProduct.Value] = v -- the button
end
end
end
MarketplaceService.ProcessReceipt = function(receiptInfo)
for i,plr in pairs(game.Players:GetPlayers()) do
if plr.userId == receiptInfo.PlayerId then
if DevProducts[receiptInfo.ProductId] then
local obj = DevProducts[receiptInfo.ProductId]
local PlrT = game.ServerStorage.PlayerMoney:WaitForChild(plr.Name).OwnsTycoon
if PlrT.Value ~= nil then
--if PlrT.Value.PurchasedObjects:FindFirstChild(obj.Object.Value) == false then
local PlayerStats = game.ServerStorage.PlayerMoney:FindFirstChild(plr.Name)
Create({[1] = 0,[2] = obj,[3] = PlayerStats}, PlrT.Value.BuyObject)
--end
end
end
end
end
end
function Create(tab, prnt)
local x = Instance.new('Model')
Instance.new('NumberValue',x).Value = tab[1]
x.Value.Name = "Cost"
Instance.new('ObjectValue',x).Value = tab[2]
x.Value.Name = "Button"
local Obj = Instance.new('ObjectValue',x)
Obj.Name = "Stats"
Obj.Value = tab[3]
x.Parent = prnt
end
Above is the script for prompts from walking over buttons.
old_fog = game.Lighting.FogStart
local MarketplaceService = game:GetService("MarketplaceService")
function getPlayerFromId(id)
for i,v in pairs(game.Players:GetChildren()) do
if v.userId == id then
return v
end
end
return nil
end
MarketplaceService.ProcessReceipt = function(receiptInfo)
local productId = receiptInfo.ProductId
local playerId = receiptInfo.PlayerId
local player = getPlayerFromId(playerId)
local productName
if productId == 1172271849 then
local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
if cashmoney then
cashmoney.Value = cashmoney.Value + 10000
end
elseif productId == 1172270951 then
local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
if cashmoney then
cashmoney.Value = cashmoney.Value + 100000
end
elseif productId == 1172270763 then
local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
if cashmoney then
cashmoney.Value = cashmoney.Value + 1000000
end
elseif productId == 1172272327 then
local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
if cashmoney then
cashmoney.Value = cashmoney.Value + cashmoney.Value
end
elseif productId == 1172273117 then
local char = player.Character
if char then
local human = char:FindFirstChild("Humanoid")
if human then
human.WalkSpeed = human.WalkSpeed + human.WalkSpeed
end
end
elseif productId == 1172273437 then
game.ServerStorage.HyperlaserGun:Clone().Parent=player.Backpack
elseif productId == 1172272691 then
game.ServerStorage.FlyingCarpet:Clone().Parent=player.Backpack
end
return Enum.ProductPurchaseDecision.PurchaseGranted
end
Above is the script for purchases from a GUI prompt.
From the Roblox manual:
As with all callbacks, this function should be set once and only once
by a single Script. If you're selling multiple products in your game,
this callback must handle receipts for all of them.
You're implementing game:GetService('MarketplaceService').ProcessReceipt in both scripts. One overwrite the other.

Lua table overridden

This is supposed to be a simple backtracking function. The dest is a global table that is being properly edited in the function. The prev table is supposed to keep track of my previous positions as to not revisit them. However, my prev table always turns out empty. I'm a novice. If there is any other helpful information I will be happy to provide it. u
function GoTo(dest, prev)
-- base case
if dest[1] == position[1] and dest[2] == position[2] and dest[3] == position[3] then
return true
end
local prev = prev or {}
-- save destination as to not return here
prev[table.concat(position)] = true
-- create key for next move
local key = {0,0,0}
for i,v in ipairs(dest) do
if dest[i] ~= 0 then
key[i] = dest[i]/math.abs(dest[i])
end
end
-- attempt to move in optimal direction
for i,v in ipairs(key) do
if key[i] ~= 0 then
-- check if next move leads to a visited destination
position[i] = position[i] + v
local check = prev[table.concat(position)]
position[i] = position[i] - v
if not check then
if moveTo(i,v) then
if GoTo(dest, prev) then
return true
end
-- go back
if not moveTo(i, -v) then
error("cannot backtrack")
end
end
end
end
end
end
local prev = prev or {}
You create a local variable in your function and initialize it from a parameter with the same name that is being passed in, which hides all the changes inside the function and that's likely why you don't see any changes for that table. You need to initialize that table outside the function and pass its value in (and remove that local prev statement).

dictionary help/DataStore

The Issue is I have a dictionary that holds all my data and its supposed to be able to turn into a directorys in replicated storage with all the values being strings then turn back into a dictionary with all the keys when the player leave. However, I cant figure out how to turn into a dictionary(With keys).
ive sat for a few hours testing things but after the first layer of values I cant get figure out a way to get the deeper values and keys into the table
local DataTable =
{
["DontSave_Values"] =
{
["Stamina"] = 100;
};
["DontSave_Debounces"] =
{
};
["TestData"] = 1;
["Ship"] =
{
["Hull"] = "Large_Ship";
["Mast"] = "Iron_Tall";
["Crew"] =
{
["Joe One"] =
{
["Shirt"] = "Blue";
["Pants"] = "Green"
};
["Joe Two"] =
{
["Shirt"] = "Silver";
["Pants"] = "Brown";
["Kids"] =
{
["Joe Mama1"] =
{
["Age"] = 5
};
["Joe Mama2"]=
{
["Age"] = 6
};
}
};
}
};
["Level"] =
{
};
["Exp"] =
{
};
}
------Test to see if its an array
function isArray(Variable)
local Test = pcall(function()
local VarBreak = (Variable.." ")
end)
if Test == false then
return true
else
return false
end
end
------TURNS INTO FOLDERS
function CreateGameDirectory(Player, Data)
local mainFolder = Instance.new("Folder")
mainFolder.Parent = game.ReplicatedStorage
mainFolder.Name = Player.UserId
local function IterateDictionary(Array, mainFolder)
local CurrentDirectory = mainFolder
for i,v in pairs(Array) do
if isArray(v) then
CurrentDirectory = Instance.new("Folder", mainFolder)
CurrentDirectory.Name = i
for o,p in pairs(v) do
if isArray(p) then
local TemporaryDir = Instance.new("Folder", CurrentDirectory)
TemporaryDir.Name = o
IterateDictionary(p, TemporaryDir)
else
local NewValue = Instance.new("StringValue", CurrentDirectory)
NewValue.Name = o
NewValue.Value = p
end
end
else
local value = Instance.new("StringValue", mainFolder)
value.Name = i
value.Value = v
end
end
end
IterateDictionary(Data, mainFolder)
end
------To turn it back into a table
function CreateTable(Player)
local NewDataTable = {}
local Data = RS:FindFirstChild(Player.UserId)
local function DigDeep(newData, pData, ...)
local CurrentDir = newData
for i,v in pairs(pData:GetChildren()) do
if string.sub(v.Name,1,8) ~= "DontSave" then
end
end
end
DigDeep(NewDataTable, Data)
return NewDataTable
end
I expected to when the player leaves run createtable function and turn all the instances in replicated storage back into a dictionary with keys.
Why not just store extra information in your data table to help make it easy to convert back and forth. As an example, why not have your data look like this :
local ExampleData = {
-- hold onto your special "DON'T SAVE" values as simple keys in the table.
DONTSAVE_Values = {
Stamina = 0,
},
-- but every element under ReplicatedStorage will be used to represent an actual Instance.
ReplicatedStorage = {
-- store an array of Child elements rather than another map.
-- This is because Roblox allows you to have multiple children with the same name.
Name = "ReplicatedStorage",
Class = "ReplicatedStorage",
Properties = {},
Children = {
{
Name = "Level",
Class = "NumberValue",
Properties = {
Value = 0,
},
Children = {},
},
{
Name = "Ship",
Class = "Model",
Properties = {},
Children = {
{
-- add all of the other instances following the same pattern :
-- Name, Class, Properties, Children
},
},
},
}, -- end list of Children
}, -- end ReplicatedStorage element
};
You can create this table with a simple recursive function :
-- when given a Roblox instance, generate the dataTable for that element
local function getElementData(targetInstance)
local element = {
Name = targetInstance.Name,
Class = targetInstance.ClassName,
Properties = {},
Children = {},
}
-- add special case logic to pull out specific properties for certain classes
local c = targetInstance.ClassName
if c == "StringValue" then
element.Properties = { Value = targetInstance.Value }
-- elseif c == "ADD MORE CASES HERE" then
else
warn(string.format("Not sure how to parse information for %s", c))
end
-- iterate over the children and populate their data
for i, childInstance in ipairs(targetInstance:GetChildren()) do
table.insert( element.Children, getElementData(childInstance))
end
-- give the data back to the caller
return element
end
-- populate the table
local Data = {
ReplicatedStorage = getElementData(game.ReplicatedStorage)
}
Now Data.ReplicatedStorage.Children should have a data representation of the entire folder. You could even save this entire table as a string by passing it to HttpService:JSONEncode() if you wanted to.
When you're ready to convert these back into instances, use the data you've stored to give you enough information on how to recreate the elements :
local function recreateElement(tableData, parent)
-- special case ReplicatedStorage
if tableData.Class == "ReplicatedStorage" then
-- skip right to the children
for i, child in ipairs(tableData.Children) do
recreateElement(child, parent)
end
-- quick escape from this node
return
end
-- otherwise, just create elements from their data
local element = Instance.new(tableData.Class)
element.Name = tableData.Name
-- set all the saved properties
for k, v in pairs(tableData.Properties) do
element[k] = v
end
-- recreate all of the children of this element
for i, child in ipairs(tableData.Children) do
recreateElement(child, element)
end
-- put the element into the workspace
element.Parent = parent
end
-- populate the ReplicatedStorage from the stored data
recreateElement( Data.ReplicatedStorage, game.ReplicatedStorage)
You should be careful about how and when you choose to save this data. If you are playing a multiplayer game, you should be careful that this kind of logic only updates ReplicatedStorage for the first player to join the server. Otherwise, you run the risk of a player joining and overwriting everything that everyone else has been doing.
Since there isn't a way to iterate over properties of Roblox Instances, you'll have to manually update the getElementData function to properly store the information you care about for each type of object. Hopefully this helps!
If anyone else has this problem the solution I used was just to convert the instances strait into JSON format(I used the names as keys). so that way I can save it, and then when the player rejoins I just used JSONDecode to turn it into the dictionary I needed.
function DirToJSON(Player)
local NewData = RS:FindFirstChild(Player.UserId)
local JSONstring="{"
local function Recurse(Data)
for i, v in pairs(Data:GetChildren()) do
if v:IsA("Folder") then
if #v:GetChildren() < 1 then
if i == #Data:GetChildren()then
JSONstring=JSONstring..'"'..v.Name..'":[]'
else
JSONstring=JSONstring..'"'..v.Name..'":[],'
end
else
JSONstring=JSONstring..'"'..v.Name..'":{'
Recurse(v)
if i == #Data:GetChildren()then
JSONstring=JSONstring..'}'
else
JSONstring=JSONstring..'},'
end
end
else
if i == #Data:GetChildren()then
JSONstring=JSONstring..'"'..v.Name..'":"'..v.Value..'"'
else
JSONstring=JSONstring..'"'..v.Name..'":"'..v.Value..'",'
end
end
end
end
Recurse(NewData)
JSONstring = JSONstring.."}"
return(JSONstring)
end

Cloning+Dragging model when button is click ROBLOX [LUA]?

So I thought of having this for so long, I just don't know where to start. I am new to this language and I keep learning, but kind of hard for me. But I have built my very own custom character which took 2 weeks for me. Anyway, For my question. An example is if I have a button and I click it, a model will be clone and I can drag that model and put it anywhere nearby. What possible method I can use to achieve this?
First things first, I suggest for any future questions, you head over to https://scriptinghelpers.org/
now, on to your question, for cloning the model, you should use mouse.Target.Parent:Clone() or the GetTopParent(mouse.Target) function in my function library (which you can get here; http://www.roblox.com/item.aspx?id=244244638)
then deposit the model into workspace and MakeJoints()
the next step is to move the model, this can be tricky, but the simplest method is model:MoveTo(mouse.Hit.p) on mouse.Moved (but that's a little buggy)
Another method for movement would be to use the Handles class, but I'm not really familiar with it, so you'd have to figure that one out on your own.
To make the first method less buggy, I'd suggest something along the lines of
model:MoveTo(mouse.Hit.p.X, mouse.Target.Position.Y + (model:GetExtentsSize().Y / 2), mouse.Hit.p.Z)
but you'd have to set up the mouse to ignore the model, which I can't really help with.
A really good place to start is to search the free models in Studio Toolbox for a 'Dragger Tool' or 'Model Dragger Tool' and then use the script inside to get started creating your own. I have learned to create my own custom draggers by doing this and it is way easier than you may think at first. Once you find a good dragger tool to borrow code from, if you need to enhance it, you can find the dragger api in the Roblox Wiki to help you further customize it to your specific needs.
http://wiki.roblox.com/index.php?title=API:Class/Dragger
EDIT: So here's the first dragger script that showed when I searched. It will drag models and parts but you will have to edit it to meet your requirements using the dragger api. Create a Tool in player.BackPack then create a LocalScript inside the Tool then copy and paste the code below into the LocalScript, and that will get you started.
local Tool = script.Parent
enabled = true
local origTexture = Tool.TextureId
game:GetService("ContentProvider"):Preload("rbxasset://icons/freemove_sel.png")
local selectionBox
local currentSelection
local currentSelectionColors = {}
local selectionLasso
local inGui = false
local inPalette = false
local lockTime = 0
function canSelectObject(part)
return part and not (part.Locked) and (part.Position - script.Parent.Parent.Head.Position).Magnitude < 60
end
function findModel(part)
while part ~= nil do
if part.className == "Model" then
return part
end
part = part.Parent
end
return nil
end
function startDrag(mousePart, hitPoint, collection)
dragger = Instance.new("Dragger")
pcall(function() dragger:MouseDown(mousePart, hitPoint, collection) end)
end
function collectBaseParts(object, collection)
if object:IsA("BasePart") then
collection[#collection+1] = object
end
for index,child in pairs(object:GetChildren()) do
collectBaseParts(child, collection)
end
end
function onMouseDown(mouse)
mouse.Icon ="rbxasset://textures\\GrabRotateCursor.png"
local part = mouse.Target
if canSelectObject(part) then
local hitPoint = mouse.Hit:toObjectSpace(part.CFrame).p
if trySelection(part) then
local instances = {}
collectBaseParts(currentSelection, instances)
startDrag(part, hitPoint, instances)
return
end
end
--Clear the selection if we weren't able to lock succesfullu
onMouseUp(mouse)
end
function onMouseUp(mouse)
mouse.Icon ="rbxasset://textures\\GrabCursor.png"
if dragger ~= nil then
pcall(function() dragger:MouseUp() end)
dragger = nil
end
end
function trySelection(part)
if canSelectObject(part) then
selectionLasso.Part = part
local model = findModel(part)
if model then
return setSelection(model)
else
return setSelection(part)
end
else
clearSelection()
return false
end
end
function onKeyDown(key)
if dragger ~= nil then
if key == 'R' or key == 'r' then
dragger:AxisRotate(Enum.Axis.Y)
elseif key == 'T' or key == 't' then
dragger:AxisRotate(Enum.Axis.Z)
end
end
end
local alreadyMoving
function onMouseMove(mouse)
if alreadyMoving then
return
end
alreadyMoving = true
if dragger ~= nil then
--Maintain the lock
if time() - lockTime > 3 then
Instance.Lock(currentSelection)
lockTime = time()
end
--Then drag
pcall(function() dragger:MouseMove(mouse.UnitRay) end)
else
trySelection(mouse.Target)
end
alreadyMoving = false
end
function saveSelectionColor(instance)
if instance:IsA("BasePart") then
currentSelectionColors[instance] = instance.BrickColor
if instance.BrickColor == BrickColor.Blue() then
instance.BrickColor = BrickColor.new("Deep blue")
else
instance.BrickColor = BrickColor.Blue()
end
end
local children = instance:GetChildren()
if children then
for pos, child in pairs(children) do
saveSelectionColor(child)
end
end
end
function setSelection(partOrModel)
if partOrModel ~= currentSelection then
clearSelection()
if Instance.Lock(partOrModel) then
lockTime = time()
currentSelection = partOrModel
saveSelectionColor(currentSelection)
selectionBox.Adornee = currentSelection
return true
end
else
if currentSelection ~= nil then
if time() - lockTime > 2 then
--Maintain the lock
if not(Instance.Lock(currentSelection)) then
--we lost the lock
clearSelection()
return false
else
lockTime = time()
return true
end
else
return true
end
end
end
return false
end
function clearSelection()
if currentSelection ~= nil then
for part, color in pairs(currentSelectionColors) do
part.BrickColor = color
end
selectionBox.Adornee = nil
Instance.Unlock(currentSelection)
end
currentSelectionColors = {}
currentSelection = nil
selectionLasso.Part = nil
selectionBox.Adornee = nil
end
function onEquippedLocal(mouse)
Tool.TextureId = "rbxasset://icons/freemove_sel.png"
local character = script.Parent.Parent
local player = game.Players:GetPlayerFromCharacter(character)
inGui = false
inPalette = false
mouse.Icon ="rbxasset://textures\\GrabCursor.png"
mouse.Button1Down:connect(function() onMouseDown(mouse) end)
mouse.Button1Up:connect(function() onMouseUp(mouse) end)
mouse.Move:connect(function() onMouseMove(mouse) end)
mouse.KeyDown:connect(function(string) onKeyDown(string) end)
selectionBox = Instance.new("SelectionBox")
selectionBox.Name = "Model Delete Selection"
selectionBox.Color = BrickColor.Blue()
selectionBox.Adornee = nil
selectionBox.Parent = player.PlayerGui
selectionLasso = Instance.new("SelectionPartLasso")
selectionLasso.Name = "Model Drag Lasso"
selectionLasso.Humanoid = character.Humanoid
selectionLasso.archivable = false
selectionLasso.Visible = true
selectionLasso.Parent = game.workspace
selectionLasso.Color = BrickColor.Blue()
alreadyMoving = false
end
function onUnequippedLocal()
Tool.TextureId = origTexture
clearSelection()
selectionBox:Remove()
selectionLasso:Remove()
end
Tool.Equipped:connect(onEquippedLocal)
Tool.Unequipped:connect(onUnequippedLocal)

Resources