Saving Player Data in RLua - lua

Is there a reason why these do not work?
Player joining script:
local DataStore = game:GetService("DataStoreService"):GetDataStore("GeneralStats")
game.Players.PlayerAdded:connect(function(player)
local stats = Instance.new("IntValue", player)
stats.Name = "leaderstats"
local points = Instance.new("IntValue", stats)
points.Name = "Points"
local credits = Instance.new("IntValue", stats)
credits.Name = "Credits"
local key = "player-"..player.userId
local savedValues = DataStore:GetAsync(key)
if savedValues then
--Save format: (points, credits)
points.Value = savedValues[1]
credits.Value = savedValues[2]
else
local ValuesToSave = {points.Value, credits.Value}
DataStore:SetAsync(key, ValuesToSave)
end
end)
And this other script for when the player leaves.
local DataStore = game:GetService("DataStoreService"):GetDataStore("GeneralStats")
game.Players.PlayerRemoving:connect(function(player)
local key = "player-"..player.userId
--Save key: {points, credits}
local valuesToSave = {player.leaderstats.Points.Values, player.leaderstats.Credits.Values}
DataStore:SetAsync(key, valuesToSave)
end)
This is for a game I am working on, justify (RLua is Roblox Lua, if you didn't know).

Yes, more than likely the leaderstat is being removed before you have a chance to extract data.
I would suggest not using leaderstats as reference for data. It's better to store data on the script directly.
However, if you truly must use leaderstats, parent it to somewhere else, extract data, then remove it.
local lead = player.leaderstats
lead.Parent = game
-- extract data
lead:Destroy()
Or you could define all those objects in a variable before they get reparented.
But again, I highly suggest not to use leaderstats for data saving. Exploiters can change that data easily and change the value to a high number.

Related

Roblox money distribution system not working

enter image description hereI was trying to make a money collection system for the person on the stone grey team, but it won't work. What it should do is take the wealth value from the province, multiply by 0.02 and add that onto the total amount of money for the person. The leaderboard has the 'Finances' on there, but the value stays at 0 no matter what. The output bar is also blank.
local map = game.Workspace.map
local rp = game:GetService("ReplicatedStorage")
local provinces = {
map.province1,
map.province2,
map.province3,
map.province4,
map.province5,
map.province6,
map.province7,
map.province8,
map.province9
}
game.Players.PlayerAdded:Connect(function(plr)
local stats = Instance.new("BoolValue")
stats.Name = "leaderstats"
stats.Parent = plr
local finances = Instance.new("NumberValue")
finances.Name = "Finances"
finances.Parent = plr.leaderstats
end)
-- below here i have problems, above this seems to work normally
rp.TaxPaymentsCheque.OnServerEvent:Connect(function(plr)
for start = 1, #provinces do
local provincegrowing = provinces[start]
if provincegrowing.BrickColor == BrickColor.new("Dark stone grey") then
local finances = plr.leaderstats.Finances.Value
local wealth = provincegrowing.ProvinceWealth.Value
local taxmodifier = 0.02
local revenue = wealth * taxmodifier
local oldfinanceamount = finances
finances = oldfinanceamount + revenue
end
end
end)
There is also a picture if it can be of any use.
So the reason why you don't see any change is because you're not actually changing the Finances Value
Instead what you are doing is saving Finances' Value to a variable and changing the variable
local number = SomeIntValue.Value
number = number * 5
-- is practically the same as saying
local number = 1
number = number * 5
It doesn't actually set the IntValue's value
To do that, do something like this
local number = SomeIntValue.Value
number = number * 5
SomeIntValue.Value = number
-- or
SomeIntValue.Value = SomeIntValue.Value * 5

Roblox Item is lagging

I add a mesh to follow the player where ever he goes. But the mesh is lagging a bit when the player runs. I understand that it is not rendering quickly enough, but anyone know how to add a mesh without it lagging?
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
RunService.Stepped:Connect(function()
local location = humanoidRootPart.CFrame
backpackItemWorkspace.CFrame = location * CFrame.new(2, 2, 3)
end)
Connect the mesh and rootpart using a weld, so you dont need to use RunService to move the mesh everytime.
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
function attach(hroot, mesh)
local weld = Instance.new("WeldConstraint", mesh)
local location = hroot.CFrame
mesh.CFrame = location + Vector3.new(2, 2, 3)
weld.Part0 = hroot
weld.Part1 = mesh
return weld
end
attach(humanoidRootPart, backpackItemWorkspace)
-- please comment if it makes any errors
Ok, for others struggling with having a pet(mesh) follow you smoothly and always stay on your back. I have now spent several hours on this subject and finally got it to work. This is how you do it:
local character = player.Character
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
//where you copy you pet from
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
//where you keep your pets in the workspace
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
//call the function for attaching the pet
attachPet(backpackItemWorkspace, character, humanoidRootPart)
function attachPet (pet, char, humanoidRootPart)
local focusPart = humanoidRootPart
local newPet = pet
local z = -5
local x = 1
local bodyPos = Instance.new("BodyPosition")
bodyPos.Parent = newPet
bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
local bodyGyro = Instance.new("BodyGyro")
bodyGyro.Parent = newPet
bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
while wait() do
bodyPos.Position = focusPart.Position + focusPart.CFrame.LookVector * z + focusPart.CFrame.RightVector * x
bodyGyro.CFrame = focusPart.CFrame
end
end
Also when you unequip a pet you have to Destroy it from where you store it. In my case I store them in a folder on the player which I call collectionInventory.
local collectionInventory = player:WaitForChild("CollectionInventory")
collectionInventory[petName]:Destroy()
Hope this save anybody else from wasting several hours with research. Even though you will probably learn a lot from those "wasted hours" ;)

Roblox Lua trying to tween part to move back and fourth like a platform

I've been practicing tweening on Lua and I'm struggling to understand why I can't get my platform to move back and fourth between a start and an end platform. First I'll show the code
-- Starting Variables
local TweenService = game:GetService("TweenService")
local group = game.Workspace.MovingPlatform
-- Group Variables
local part = group.Platform
local start = group.Check1
local finish = group.Check2
-- Vectors
local destination = Vector3.new(start.Position.x,start.Position.y, start.Position.z)
-- Platform Tween Info
local info = TweenInfo.new(
1, --Length (seconds)
Enum.EasingStyle.Linear,
Enum.EasingDirection.Out,
-1,--Times To Be Repeated
true,
0 --Delay
)
-- Where the destination is
local Goals = {
Position = Vector3.new(destination)
}
-- Makes it go
local MovePart = TweenService:Create(part, info, Goals)
MovePart:Play()
-- Debugging
local startPosition = Vector3.new(start.Position.x, start.Position.y, start.Position.z)
local endPosition = Vector3.new(finish.Position.x, finish.Position.y, finish.Position.z)
local partPosition = Vector3.new(part.Position.x, part.Position.y, part.Position.z)
while true do
print("Start Position: "..tostring(startPosition))
print("Destination: "..tostring(destination))
print("End Position: "..tostring(endPosition))
print("Platform Position: "..tostring(partPosition))
print("--------------")
wait(3)
end
The platform will move once and then start bugging out and going anywhere and eventually will rest on the floor moving back and fourth but not at the correct location. I've tried debugging to see if the positioning of any of my parts were somehow changing but everything stayed the same. Maybe I'm not logging the positions correctly but nonetheless any hints at what I could be doing wrong?
You might want to try using CFrame instead of Position when moving things.
Also, Part.Position is a Vector3 so there's no point in creating a new Vector3 for a Vector3.
Try something like this:
-- Starting Variables
local TweenService = game:GetService("TweenService")
local group = game.Workspace.MovingPlatform
-- Group Variables
local part = group.Platform
local start = group.Check1
local finish = group.Check2
-- Set the platform part to start at Check1
part.CFrame = start.CFrame
-- Platform Tween Info
local info = TweenInfo.new(
1, --Length (seconds)
Enum.EasingStyle.Linear,
Enum.EasingDirection.Out,
-1,--Times To Be Repeated
true,
0 --Delay
)
-- Where the destination is
local Goals = {
CFrame = finish.CFrame -- We want it to end at the finish part's position
}
-- Makes it go
local MovePart = TweenService:Create(part, info, Goals)
MovePart:Play()

Can't get to a value inside a player in lua

Code I Tried
game.Workspace.burgerclick.OnServerEvent:Connect(function()
local playername = game.Workspace.ClickPlayer.Value
local player = game.Players:FindFirstChild(playername)
local playaname = player.Name
local fpval = game.Players[playaname].FP.Value
fpval = fpval + 1
end)
I am making a game and I wanted to have a button that updates the value of something called FP, in the workspace I have a stringvalue called ClickPLayer which updates to the player clicking the button. that works. I made a variable that is the value the stringvalue, but when I put the variable inside the line when I update the FP Value it says the variable is not a valid member of players. I'm not sure what to do.
I think the correct code should be something like:
game.Players[playaname].FP.Value = game.Players[playaname].FP.Value + 1
Because, when you do:
local fpval = game.Players[playaname].FP.Value
fpval = fpval + 1
You are copying the value of game.Players[playaname].FP.Valueto fpval and incrementing the copy (fpval = fpval + 1), not the value held by game.Players[playaname].FP.
The most correct and efficient code would be
local Players = game:GetService("Players")
local fpval
local plr
workspace.burgerclick.Activated:Connect(function()
plr = workspace.ClickPlayer.Value
fpval = Players[plr].FP
fpval.Value = fpval.Value + 1
end)
In the documentation of TextButtons and ImageButtons, there is an Activated event that can be used for this, instead of firing a server from a LocalScript which is what your script aims to do now. However, if the button is in the PlayerGui and you have an activation LocalScript for it, you probably want to use this code instead:
local fpval
workspace.burgerclick.OnServerEvent:Connect(function(plr)
fpval = plr.FP
fpval.Value = fpval.Value + 1
end)

corona sdks - Why ain't my database updating count?

I seem to be having an issue with my database in corona sdk. I want to store the play counts every time a player plays the game. my project doesn't have a gamescene and plays only through menu.lua. I have set up a highscore database (which is separate from the other one but exactly the same) and it works fine and updates/loads data fine. My play count data base however doesn't work.
At first the play count increases by 1 when the game returns to menu again once its removed. But tries after that doesn't increase the value, it's like it has reset.
Globals.lua
M.plays = 0
--------------------------
local function setupDatabase2()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open( dbPath )
local tablesetup1 = [[
CREATE TABLE played (id INTEGER PRIMARY KEY, plays);
INSERT INTO played VALUES (NULL, '0');
]]
db:exec( tablesetup1 ) --Create it now.
db:close() --Then close the database
end
setupDatabase2()
M.loadAppInfo = function()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open(dbPath)
for row in db:nrows("SELECT * FROM played WHERE id = 1") do
M.plays = tonumber(row.plays)
end
db:close()
end
M.saveAppInfo = function()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open(dbPath)
local update = "UPDATE played SET plays='" .. M.plays .."' WHERE id=1"
db:exec(update)
db:close()
end
return M
menu.lua
local utils = require("helpers.globals")
local play = 0
----------------------------------------
function scene:createScene( event )
local group = self.view
utils.loadHighscoreInfo() -- Separate db which is working fine
utils.loadAppInfo()
function beginGame( event )
timerSrc = timer.performWithDelay(400, createBlock, -1)
Runtime:addEventListener("enterFrame", gameLoop)
play = play +1
utils.plays = play
utils.saveAppInfo()
end
Your SQL statement is doing all of that. Your current sql creates a table everytime it is called. Try this:
local tablesetup1 = [[
CREATE TABLE IF NOT EXISTS played (id INTEGER PRIMARY KEY, plays);
INSERT INTO played VALUES (NULL, '0');]]
I guess that statement is pretty much self explanatory :)

Resources