Is there a reason why this code is not outputting a worth - lua

Problem
Hello, StackOverflow community! I am working on this Lua game, and I was testing to see if it would change the text on my TextLabel to the Bitcoins current worth, I was utterly disappointed when nothing showed up.
I have tried to do research on Google, and my code seems to be just right.
Code
Change = false
updated = false
while Change[true] do --While change = true do
worth = math.random(1,4500) --Pick random number
print('Working!') --Say its working
Updated = true --Change the updated local var.
end --Ending while loop
script.Parent.TextLabel.Text.Text = 'Bitcoin is currently worth: ' .. worth
--Going to the Text, and changing in to a New worth.
while Updated[false] do --While updated = false do
wait(180) --Wait
Change = true --After waits 3 minutes it makes an event trigger
end -- Ending while loop
wait(180) --Wait
Updated = false --Reseting Script.
I expect the output on the Label to be a random number.

I can't really speak to roblox, but there are a couple of obvious problems with your code:
Case
You have confusion between capitalized ("Updated", "Change") and lowercase ("updated", "change" [in commented while statement]), which will fail. See, for example:
bj#bj-lt:~$ lua
Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> Updated = true
> print(Updated)
true
> print(updated)
nil
So be super-careful about what identifiers you capitalize. In general, most programmers leave variables like that in all-lowercase (or sometimes things like camelCase). I suppose there might be some oddball lua runtime out there that is case-insensitive, but I don't know of one.
Type misuse.
Updated is a boolean (a true/false value), so the syntax:
while Change[true] do
...is invalid. See:
> if Updated[true] then
>> print("foo")
>> end
stdin:1: attempt to index global 'Updated' (a boolean value)
stack traceback:
stdin:1: in main chunk
[C]: in ?
Note also that the "While change == true do" is also wrong because of case ("While" is not valid lua, but "while" is).
Lastly:
Lack of threading.
You have basically two different things that you're trying to do at once, namely randomly change the "worth" variable as fast as possible (it's in a loop) and see a set a label to match it (it looks like you probably want it to change constantly). This requires two threads of operation (one to change worth and another to read it and stick it on the label). You've written this like you're assuming you have a spreadsheet or something and that. What your code is actually doing is:
Setting some variables
Updating worth indefinitely, printing 'Working!' a bunch, and...
Never stopping
The rest of the code never runs, because the rest of the code isn't in a background thread (basically the first bit monopolizes the runtime and never yields to everything else).
Lastly, even if the top code was running in the background, you only set the Text label one-time to exactly "Bitcoin is currently worth: 3456" (or some similar number) one time. The way this is written there won't be any updates thereafter (and, if it runs once before the other thread has warmed up, it might not be set to anything useful at all).
My guess is that your runtime is spitting out errors left and right due to the identifier problems and/or is running in a tight infinite loop and never actually getting to the label refresh logic.

BJ Black has given an excellent description of the issues with the syntax, so I'll try to cover the Roblox piece of this. In order for this kind of thing to work properly in a Roblox game, here are some assumptions to double check :
Since we are working with a TextLabel, is it inside a ScreenGui? Or a SurfaceGui?
If it's in a ScreenGui, make sure that ScreenGui is in StarterGui, and is this code in a LocalScript
If it's in a SurfaceGui, make sure that SurfaceGui is adorning a Part and this code
is in a Script
After you checked all those pieces, maybe this is closer to what you were thinking :
-- define the variables we're working with
local textLabel = script.Parent.TextLabel
local worth = 0
-- create an infinite loop
spawn(function()
while true do
--Pick random number
worth = math.random(1,4500)
-- update the text of the label with the new worth
textLabel.Text = string.format("Bitcoin is currently worth: %d", worth)
-- wait for 3 minutes, then loop
wait(180)
end
end)
I removed Updated and Changed because all they were doing was deciding whether or not to change the value. The flow of your loop was:
do nothing and display an undefined number. Wait 3 minutes
update the number, display it, wait 6 minutes
repeat 1 and 2.
So hopefully this is a little clearer and closer to what you were thinking.

Related

Fixing my color touch script for my roblox puzzle game

So I have a roblox puzzle game that I have been working on for a while now on based on the arcade classic Q bert where the goal is to change all the colours of the bricks while avoiding enemies and getting a high score but I will be adding some features of my own so it does not get as repetitive such as additional tasks like collecting keys on platforms to unlock the door to the next level and secrets like a diamond that rarely appears once every 10 rounds and collecting one gives the player an extra dude and 10 million points.
This is how the game looks so far https://streamable.com/na46cu
The issue I am having as you can see is that the colours do in fact change but when I jump on it again it changes back to the first colour it changes to which in this case is green but I want it to stay on the first colour and make it so that it does not change until the player jumps on the brick again and later on in the game I want it to become more complex and puzzle like as the game goes on like in this example [https://www.youtube.com/watch?v=9eXJWiNXpOo][2] .
I have tried a few things like adding timers ,debounces and even separate scripts alltogether none of which have worked out for me so far and I of course went out looking for a question from somebody else that had a similar problem but so far I have been struggling to find anybody else that has the same problem.
local module = {} --module for the modulescript and for loop is created
local CollectionService = game:GetService("CollectionService")
for _, part,brick in pairs (CollectionService:GetTagged("blocks"))
do
part.Touched:Connect(function(hit) --Part connects with the touched property to the function with the parameter hit
if (hit.Parent:FindFirstChild("Humanoid"))
then
part.BrickColor = BrickColor.new ("Bright green")
wait (2)
part.BrickColor = BrickColor.new ("Eggplant")
-- local sound = workspace.Sound -- use "local sound = workspace.Sound", if there is already a sound object in the workspace
--sound.SoundId = "rbxassetid://4797903038" --replace quoted text with whatever sound id you need to use
--sound:Play()
end
end)
end
-- end)
--end
return module
I am not the best programmer but I do know the basics of programming and I have tried out various programming languages like Python and c++ all of which are not all that hard to understand once you know the basics of it all but finding out the solution to the problem is the really tricky part and so is bug fixing and troubleshooting.
I do know I could try a simple debounce system but that still does not solve the problem and it only makes it so the code only runs once and slows it down.
I have been asking all over the place for a solution to this problem but I never got an answer to it so I am trying on good old Stackoverflow for once to see if this will be the place where I get the help I need.
this should work, try it
local module = {} --module for the modulescript and for loop is created
local CollectionService = game:GetService("CollectionService")
local DidParts = {} -- Initializing another table to check if the part is already in it
for _, part,brick in pairs(CollectionService:GetTagged("blocks")) do
part.Touched:Connect(function(hit) --Part connects with the touched property to the function with the parameter hit
if hit.Parent:FindFirstChild("Humanoid") then
if table.find(DidParts,part) then
return -- checking if the part isnt in the table if it is then return
end
part.BrickColor = BrickColor.new("Bright green")
wait(2)
part.BrickColor = BrickColor.new("Eggplant")
table.insert(DidParts,part) -- when all the code has finished insert it in the table
-- local sound = workspace.Sound -- use "local sound = workspace.Sound", if there is already a sound object in the workspace
--sound.SoundId = "rbxassetid://4797903038" --replace quoted text with whatever sound id you need to use
--sound:Play()
end
end)
end
-- end)
--end
return module

(Lua) How do I increment a variable every time one of three if statements runs?

I'm building a moving and sensing bot in CoppelliaSim for school. CopelliaSim uses Lua for scripting. Basically every time the bot's forward sensors hit something, one of three if statements will run. I want it to count how many times any of these if statements runs, and once that count gets to a certain amount (like 20), I'll run something else, which will do the same thing (find collisions, add to the count, reach an amount, and switch back to the first).
i=0
result=sim.readProximitySensor(noseSensor) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
result=sim.readProximitySensor(noseSensor0) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
result=sim.readProximitySensor(noseSensor1) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
Above is the start of a function and one of the three If statements. I'm printing just to see if it actually increments. It is printing, but it is not incrementing (just 1 over and over). This bot has 3 sensors on it (an if statement for each sensor) and it adds 1 to i for the first collision and ignores the rest, even if it's from the same sensor. I feel like my problem is just some simple syntax issue with Lua that I don't know and can't find how to properly fix.
I'm happy to provide more code if this little snippet was not sufficient to answer this question.
Assuming that you have a looping function such as sysCall_actuation which is being executed per simulation step. As Joseph Sible-Reinstate Monica has already stated, you are setting your variable i back to zero every time a simulation step is executed. To achieve your goal, you would have to set your variable to 0 outside your function. There are two appropriate approaches to achieve that:
Define the variable outside any function, in the beginning of your file (or before you define any function that uses your variable e.g right before the definition of sysCall_actuation).
-- Beginning of the file.
local i = 0
..
function sysCall_actuation()
..
i = i + 1
..
end
Define your variable in sysCall_init function, which is the appropriate approach in CoppeliaSim.
function sysCall_init()
i = 0
..
end
Finally, you can use your variable in your sysCall_actuation function with basic comparison operations:
function sysCall_actuation()
..
if i > 20 then
i = 0 -- Reset 'i' so this function will not be running every step again and again.
-- Do something here.
..
end
As a side note, practice using local variables whenever you can, to keep the memory clean and avoid having ambiguous variables.

Script stops after a few seconds

I have this exploit for Murder Mystery 2.
It is a tpcoins and esp exploit. When I enable the tpcoins it will turn off after a few seconds. Is there any way of making it so it stays on?
Here's the code:
function enableTpCoin()
if nameMap ~= "" and wp[nameMap] ~= nil then
if lplr.PlayerGui.MainGUI.Game.CashBag:FindFirstChild("Elite") then
tpCoin(10)
elseif lplr.PlayerGui.MainGUI.Game.CashBag:FindFirstChild("Coins") then
tpCoin(15)
end
end
Trigger to start the script is q.
Short answer, you can't. Since this is script related I'll answer your question.
So each round, the player can only earn 10 coins, and 15 if they have purchased the "Elite" gamepass.
This meaning that the game physically doesn't allow you to add anymore per round. You'll have to execute the code at the launch of every round.
The game has FE, so it's most likely that the original developer of the game has specified the remote events to only accept 10 or 15 coins depending on the boolean value whether the user is "Elite" or not.
Even if Universal Link says the truth, here's the solution.
Create a new function. In that function, do a while loop with a interval (use wait(.1)), and in that while loop, call enableTpCoin().
Now, call spawn() and pass the function you created as an argument.
The code should look like this:
function _loop()
while wait(.1) do
enableTpCoin()
end
end
spawn(_loop)

Can't modify loop-variable in lua [duplicate]

This question already has answers here:
Lua for loop reduce i? Weird behavior [duplicate]
(3 answers)
Closed 7 years ago.
im trying this in lua:
for i = 1, 10,1 do
print(i)
i = i+2
end
I would expect the following output:
1,4,7,10
However, it seems like i is getting not affected, so it gives me:
1,2,3,4,5,6,7,8,9,10
Can someone tell my a bit about the background concept and what is the right way to modify the counter variable?
As Colonel Thirty Two said, there is no way to modify a loop variable in Lua. Or rather more to the point, the loop counter in Lua is hidden from you. The variable i in your case is merely a copy of the counter's current value. So changing it does nothing; it will be overwritten by the actual hidden counter every time the loop cycles.
When you write a for loop in Lua, it always means exactly what it says. This is good, since it makes it abundantly clear when you're doing looping over a fixed sequence (whether a count or a set of data) and when you're doing something more complicated.
for is for fixed loops; if you want dynamic looping, you must use a while loop. That way, the reader of the code is aware that looping is not fixed; that it's under your control.
When using a Numeric for loop, you can change the increment by the third value, in your example you set it to 1.
To see what I mean:
for i = 1,10,3 do
print(i)
end
However this isn't always a practical solution, because often times you'll only want to modify the loop variable under specific conditions. When you wish to do this, you can use a while loop (or if you want your code to run at least once, a repeat loop):
local i = 1
while i < 10 do
print(i)
i = i + 1
end
Using a while loop you have full control over the condition, and any variables (be they global or upvalues).
All answers / comments so far only suggested while loops; here's two more ways of working around this problem:
If you always have the same step size, which just isn't 1, you can explicitly give the step size as in for i =start,end,stepdo … end, e.g. for i = 1, 10, 3 do … or for i = 10, 1, -1 do …. If you need varying step sizes, that won't work.
A "problem" with while-loops is that you always have to manually increment your counter and forgetting this in a sub-branch easily leads to infinite loops. I've seen the following pattern a few times:
local diff = 0
for i = 1, n do
i = i+diff
if i > n then break end
-- code here
-- and to change i for the next round, do something like
if some_condition then
diff = diff + 1 -- skip 1 forward
end
end
This way, you cannot forget incrementing i, and you still have the adjusted i available in your code. The deltas are also kept in a separate variable, so scanning this for bugs is relatively easy. (i autoincrements so must work, any assignment to i below the loop body's first line is an error, check whether you are/n't assigning diff, check branches, …)

Lua - Couple Questions

Im a amatuer at coding. So, mind me if i face palmed some things.
Anyways, im making a alpha phase for a OS im making right? I'm making my installer. Two questions. Can i get a code off of pastebin then have my lua script download it? Two. I put the "print" part of the code in cmd. I get "Illegal characters". I dont know what went wrong. Here's my code.
--Variables
Yes = True
No = False
--Loading Screen
print ("1")
sleep(0.5)
print("2")
sleep(0.5)
print("Dowloading OS")
sleep(2)
print("Done!")
sleep(0.2)
print("Would you like to open the OS?")
end
I see a few issues with your code.
First of all, True and False are both meaningless names - which, unless you have assigned something to them earlier, are both equal to nil. Therefore, your Yes and No variables are both set to nil as well. This isn't because true and false don't exist in lua - they're just in lowercase: true and false. Creating Yes and No variables is redundant and hard to read - just use true and false directly.
Second of all, if you're using standard lua downloaded from their website, sleep is not a valid function (although it is in the Roblox version of Lua, or so I've heard). Like uppercase True and False, sleep is nil by default, so calling it won't work. Depending on what you're running this on, you'll want to use either os.execute("sleep " .. number_of_seconds) if you're on a mac, or os.execute("timeout /t " .. number_of_seconds) if you're on a PC. You might want to wrap these up into a function
function my_sleep_mac(number_of_seconds)
os.execute("sleep " .. number_of_seconds)
end
function my_sleep_PC(number_of_seconds)
os.execute("timeout /t " .. number_of_seconds)
end
As for the specific error you're experiencing, I think it's due to your end statement as the end of your program. end in lua doesn't do exactly what you think it does - it doesn't specify the end of the program. Lua can figure out where the program ends just by looking to see if there's any text left in the file. What it can't figure out without you saying it is where various sub-blocks of code end, IE the branches of if statements, functions, etc. For example, suppose you write the code
print("checking x...")
if x == 2 then
print("x is 2")
print("Isn't it awesome that x is 2?")
print("x was checked")
lua has no way of knowing whether or not that last statement, printing the x was checked, is supposed to only happen if x is 2 or always. Consequently, you need to explicitly say when various sections of code end, for which you use end. For a file, though, it's unnecessary and actually causes an error. Here's the if statement with an end introduced
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
although lua doesn't care, it's a very good idea to indent these sections of code so that you can tell at a glance where it starts and ends:
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
with regards to your "pastebin" problem, you're going to have to be more specific.
You can implement sleep in OS-independent (but CPU-intensive) way:
local function sleep(seconds)
local t0 = os.clock()
repeat
until os.clock() - t0 >= seconds
end

Resources