function saveScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local score=get_score() --The get_score() returns the value of current score which is saved in 'score'.
local newScore = compareScore()
local contents = tostring( newScore )
file:write( contents )
io.close( file )
return true
else
print("Error: could not write Score")
return false
end
end
function loadScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local contents = ""
local file = io.open( path, "r" )
if file then
local contents = file:read( "*a" )
local score = tonumber(contents);
io.close( file )
return score
end
print("Could not read scores from scoredata.txt")
return nil
end
function return_highScore()
local highscore=loadScore()
if highscore==nil then
highscore=0
end
return highscore
end
function compareScore()
local highscore=return_highScore()
if highscore then
local currscore=get_score()
if highscore==0 then
return highscore
elseif currscore>highscore then
return currscore
end
end
return true
end
function disp_permScore()
local display_score=return_highScore()
text_display2= display.newText("GAME OVER!\n BEST: " ..display_score, 0, 0, "Helvetica", 80)
text_display2.x = centerX
text_display2.y = centerY
text_display2.alpha=1
function gameOver()
mainScreen()
saveScore()
disp_permScore()
end
(This is with refernce to previous question Permission issues in lua )
Basically I'm trying to build a game in lua (This is my first ever game)
But, I'm unable to save highscore to file. If it gets saved, then I'm unable to retrieve them. (In short, I always some or the other error/problem in executing the code.
Please have a look at the code above. I want to display both high score and current score. Current score is being displayed perfect. This is something I tried yesterday night. But now, the high score is not being saved in file. (i.e. the best always displays 0) Also, the cmd says "unable to read scores form scoredata.txt) I'm unable to find where I went wrong.
Please help with this?
Please tell where do I go wrong?
Also, if possible, provide (or edit) the correct code please?
There seems to be a problem on this line
if highscore==0
then
return highscore
Meaning you check if the highscore is 0 and if it is then you return it instead of the actual higher score.
Also, I don't know if your code was just pasting error, but without indenting your code it becomes really hard to read. Try and look again I indentet it and now the error becomes really easy to spot.
Related
Hello I am having the above error in production but all works well in development. I am using the code bellow to get the path to the main image for the property but it defaults into the else despite the if not being false plus the else does not find the paths even when dump shows that the object has been returned
//check if there are hotels in the selected destination
if($hotels->isNotEmpty()){
//Loop through the hotels
foreach($hotels as $hotel){
//get hotels main image
$banner = Photo::where(['p_id'=>$hotel->id])->where(['is_main'=>1])->first();
$altbanner = Photo::where(['p_id'=>$hotel->id])->first();
$banner_path = "";
$altText = "";
if($banner!=null){
$banner_path = $banner->path;
$altText = $banner->alt_text;
}else{
$banner_path = $altbanner->path;
$altText = $altbanner->alt_text;
}
Have you checked your database if each hotel has an image? Based on your question and explanation, there is a part of the for each that returns null for the image hence the if part fails and the else return the error. If that is the case then you may want to check and sort it by uploading the image or modifying your checks to handle cases where no image is found.
I think the way you are using the where clause isn't right
foreach($hotels as $hotel){
//get hotels main image
$banner = Photo::where('p_id',$hotel->id)->where('is_main',1)->first();
$altbanner = Photo::where('p_id',$hotel->id)->first();
// .....
if($banner){
$banner_path = $banner->path;
// ......
I made this code thinking it would allow the player to jump Twice and the second Jump be the power of its leader stat but Instead it doesn't even allow the player to Jump a second time.
local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character
local humanoid
local canDoubleJump = false
local hasDoubleJumped = false
local oldPower
local time_delay = 0.2
local jump_multiplier = player.leaderstats.JumpBoost.Value
function onJumpRequest()
if not character or not humanoid or not
character:IsDescendantOf(workspace) or humanoid:GetState() ==
Enum.HumanoidStateType.Dead then
return
end
if canDoubleJump and not hasDoubleJumped then
hasDoubleJumped = true
humanoid.JumpPower = oldPower * jump_multiplier
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
local function characterAdded(new)
character = new
humanoid = new:WaitForChild("Humanoid")
hasDoubleJumped = false
canDoubleJump = false
oldPower = humanoid.JumpPower
humanoid.StateChanged:connect(function(old, new)
if new == Enum.HumanoidStateType.Landed then
canDoubleJump = false
hasDoubleJumped = false
humanoid.JumpPower = oldPower
elseif new == Enum.HumanoidStateType.Freefall then
wait(time_delay)
canDoubleJump = true
end
end)
end
if player.Character then
characterAdded(player.Character)
end
player.CharacterAdded:connect(characterAdded)
UIS.JumpRequest:connect(onJumpRequest)
I expected the player to Jump Twice with the second Jump having the power of the leader stat(I only put that and this because it says it wants more detail)
LocalScripts do not execute in game.Workspace: they only run on clients, hence the term 'local'; Scripts, on the other hand, are server-side.
You could use a Script to place your double-jump script--a LocalScript--into incoming players' character models.
-- Server-side Script
local players = game:GetService("Players")
local jumpScript = script:WaitForChild("JumpScript") -- Assume the double-jump script is a LocalScript called 'JumpScript'.
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
-- Check to make sure the character model does not already contain the double-jump script, just in case.
local clone = char:FindFirstChild("JumpScript")
if (not clone) then
clone = jumpScript:Clone()
clone.Parent = char
end
end)
end)
As a note, it is good practice to put server-side scripts like this into ServerScriptStorage instead of workspace or Lighting. (You can read about the safety of ServerScriptStoragehere.)
In Roblox, your camera has a CFrame with a lookVector and so on. What I'm trying to accomplish is to detect when a player has pressed their right mouse button, and through a loop, rotate their character based on the CFrame of the camera until the button is released.
I've pretty much got it, but instead of rotating the character model, it turns the screen black and kills the player. I've seen this done in RPGs on Roblox before, so I know it's possible, and probably fairly easy. I've worked with CFrames quite a bit in the past, so I'm not sure why I'm having such a hard time with this.
After a couple hours of playing around with ideas and checking online, I thought I'd just ask the question to save time. What's the correct way to achieve this?
Edit: My bad, this is what I have so far. I fixed the black screen, but the player still just dies.
local UIS,Player,Camera,Character,MB2Down = game:GetService('UserInputService'),game.Players.LocalPlayer,workspace.Camera,script.Parent,false
local Torso = Character:FindFirstChild('Torso') or Character:FindFirstChild('UpperTorso')
UIS.InputEnded:Connect(function(Input)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and MB2Down then
MB2Down = false
Character.Humanoid.AutoRotate = true
end
end)
UIS.InputBegan:connect(function(Input,onGui)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and not onGui then
MB2Down = true
Character.Humanoid.AutoRotate = false
while MB2Down and wait() do
Torso.CFrame = CFrame.new(Vector3.new(Torso.CFrame),Vector3.new(Camera.CFrame.p))
end
end
end)
You've almost got it, but let me take a slightly different approach to my solution. When the player presses the right mouse button, let's connect a function to the Heartbeat event that will update the character's rotation to the camera's. Also, we will rotate the HumanoidRootPart instead of the Torso/UpperTorso. The HumanoidRootPart is the PrimaryPart of the character model, and thus is the part we should manipulate if we want to manipulate the model as a whole.
The way we will lock the player's rotation to the camera is as follows:
Get the position of the character.
Get the rotation of the camera (by using arc-tangent and camera's look-vector).
Construct the new CFrame for the player using the position and rotation from steps 1 and 2.
Apply the CFrame to the character's HumanoidRootPart.
The following code is in a LocalScript and is placed under StarterCharacterScripts:
local userInput = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character = script.Parent
local root = character:WaitForChild("HumanoidRootPart")
local humanoid = character:WaitForChild("Humanoid")
local camera = workspace.CurrentCamera
local dead = false
local heartbeat = nil
function LockToCamera()
local pos = root.Position
local camLv = camera.CFrame.lookVector
local camRotation = math.atan2(-camLv.X, -camLv.Z)
root.CFrame = CFrame.new(root.Position) * CFrame.Angles(0, camRotation, 0)
end
userInput.InputEnded:Connect(function(input)
if (input.UserInputType == Enum.UserInputType.MouseButton2 and heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
humanoid.AutoRotate = true
end
end)
userInput.InputBegan:Connect(function(input, processed)
if (processed or dead) then return end
if (input.UserInputType == Enum.UserInputType.MouseButton2) then
humanoid.AutoRotate = false
heartbeat = game:GetService("RunService").Heartbeat:Connect(LockToCamera)
end
end)
humanoid.Died:Connect(function()
dead = true
if (heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
end
end)
Let me know if you need any clarification.
I have a part of a lua script here:
local cmp = require("component")
local r = cmp.br_reactor
local e = require("event")
local unicode = require ("unicode")
local exit = false
local buffersize = 10000000
local last_tick_percent = 1
print(type(last_tick_percent))
function stored_energy()
local rf_stored = r.getEnergyStored()
local rf_percent = (rf_stored/buffersize)*100
print(type(rf_precent))
print(type(last_tick_percent))
local delta_percent = rf_percent - last_tick_percent
last_tick_percent = re_percent
return rf_percent.."% ["..rf_stored.."] | "..unicode.char(916)..": "..delta_percent.."%"
end
The first print is not even executed for some reason. Inside the function, the first print returns Number while the second print returns nil.
Now I am getting the error attempt to perform arithmetic on upvalue "last_tick_percent" ( a nil value), obviously because last_tick_percent is nil which the print(type(..)) showed.
But i just assigned it literally 5 lines above.
So the questions are:
Why is last_tick_percent nil and how can i fix that?
why is the first print not executed?
you are assigning re_percent which is not declared in your script to last_tick_percent inside stored_energy. i am assuming you meant to assign rf_percent.
Situation :
There are two sensors and I want to save the data of values of each sensor in the certain file..But it's not working. I am working on linux system and the file is still empty.
What's wrong with my code? any suggestion please?
my code is:
--Header file
require("TIMER")
require("TIMESTAMP")
require("ANALOG_IN")
function OnExit()
print("Exit code...do something")
end
function main()
timer = "TIMER"
local analogsensor_1 = "AIR_1"
local analogsensor_2 = "AIR_2"
local timestr = os.data("%Y-%m-%d %H:%M:%S")
-- open the file for writing binary data
local filehandle = io.open("collection_of_data.txt", "a")
while true do
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
-- save values of sensors
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n");
end
TIMER.sleep(timer,500)
end
-- close the file
filehandle:close()
end
print("start main")
main()
I do not know what this libs realy do.
But this code is incorrect;
1) you do not close while statement.
if in real code you close it before filehandle:close() then try call filehandle:flush()
2) you forgot comma:
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n")
(it should seay something like attemt call a number value).
3) try print out valueOfSensor_1 and valueOfSensor_2 values. May be there no data.
Beside the typos pointed out by #moteus, shouldn't this:
if (valueOfSensor_1 and valueOfSensor_2 > 0) then
be like this?
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
Edit, in response to your comment to another answer:
still error..it says "attempt to call field 'data' (a nil value)
I can't be sure without the stack trace, but, most likely, something bad happens in the ANALOG_IN library code. You may not be using it properly.
try to turn this:
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
into this:
success, valueOfSensor_1 = pcall(ANALOG_IN.readAnalogIn, analogsensor_1);
if not success then
print("Warning: error reading the value of sensor 1:\n"..valueOfSensor_1)
valueOfSensor_1 = 0
end
success, valueOfSensor_2 = pcall(ANALOG_IN.readAnalogIn, analogsensor_2);
if not success then
print("Warning: error reading the value of sensor 2:\n"..valueOfSensor_2)
valueOfSensor_2 = 0
end
If the failure in ANALOG_IN is not systematic, it will work around it. If the call fails systematically, you'll get a huge warning log, and an empty collection_of_data.txt.
Please note that ANALOG_IN is not a standard Lua library. You should check its documentation , and pay attention to the details of its usage.