Getting the value of an "IntValue" always gets default value - lua

I am a student and I am trying to get the value of an "IntValue" to use has level, what I mean by this is that I need to have a skill level for each individual player and use this skill level to multiply the amount of damage the skill does.
for example: Skill level is 5
the damage should be: baseDamage * SkillLevel
in my case. base damage is 2 so the end result should be 10 damage.
but when I try doing this whit code it doesn't work. (I'm not the best at LUA and I'm fairly new to stack so I apologize in advance)
Code (So far I got this):
local XP = 0 --Exp Amount
local LevelValue = player.Backpack.ScriptStorage.Player.SkillLevel.Value --Gets the value of the skill level from the "IntValue"
--Other code that I don't want to show (it just checks if a remote event has fired the server, and it adds .5 to the XP every time it fires)
--This is the line that should add 1 to the level
LevelValue = LevelValue + 1
--But everytime it gets to 2 it simply gets set back to 1 (the default level)
I just showed the relevant pieces of code. everything that was not relevant to this wasn't shown (except for: XP = XP + .5 which is in the code I'm not showing)
hope this helps figure out what the problem is. as said above: "I'm not the best at LUA and I'm fairly new to stack so I apologize in advance"

In your code, you store SkillLevel.Value into the LevelValue local variable. This takes a snapshot of that value and stores it in the variable. So when you modify the local variable, you are not updating the IntValue object that is storing SkillLevel.
When you want to update SkillLevel, you need to update the IntValue directly :
local SkillLevel = player.Backpack.ScriptStorage.Player.SkillLevel
local LevelValue = SkillLevel.Value
-- .. do some other stuff
-- add 1 to the level
SkillLevel.Value = SkillLevel.Value + 1

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

I am looking for a Lua find and replace logic

enter image description here
I just started working on lua scripting since a week. I have a lua file where in the logic needs to be written for a certain condition.
The condition when gets triggered
it does an iteration on one of the fields to change value from
(ABC123-XYZ) to this value
(ABC123#1-XYZ) and it keeps increasing whenever iterations happens (ABC123#2-XYZ)
I need to run a function that removes the # followed by number to change it back to (ABC123-XYZ). Looking for any advice!
Edit 1:
Below is the updated code that is written Thanks to #Piglet
I have another scenario if therr are two hashes in the variable.
local x = 'BUS144611111-PNB_00#80901#1555-122TRNHUBUS'
local b = x:gsub("#%d+","")
function remove_char(a) a=a:gsub("#%d+","")
return a;
end if string.match(x,"#")
then print('function')
print(remove_char(x));
else print(x);
end
Expected output should be
x = 'BUS144611111-PNB_00#80901-122TRNHUBUS' for the aforesaid variable
local a = "ABC123#1-XYZ"
local b = a:gsub("#%d+", "")
this will remove any # followed by or one more digits from your string.

(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.

Issue returning desired data with Lua

Wondering if I could get some help with this:
function setupRound()
local gameModes = {'mode 1','mode 2','mode 3'} -- Game modes
local maps = {'map1','map2','map3'}
--local newMap = maps[math.random(1,#maps)]
local mapData = {maps[math.random(#maps)],gameModes[math.random(#gameModes)]}
local mapData = mapData
return mapData
end
a = setupRound()
print(a[1],a[2]) --Fix from Egor
What the problem is:
`
When trying to get the info from setupRound() I get table: 0x18b7b20
How I am trying to get mapData:
a = setupRound()
print(a)
Edit:
Output Issues
With the current script I will always the the following output: map3 mode 2.
What is the cause of this?
Efficiency; is this the best way to do it?
While this really isn't a question, I just wanted to know if this method that I am using is truly the most efficient way of doing this.
First of all
this line does nothing useful and can be removed (it does something, just not something you'd want)
local mapData = mapData
Output Issues
The problem is math.random. Write a script that's just print(math.random(1,100)) and run it 100 times. It will print the same number each time. This is because Lua, by default, does not set its random seed on startup. The easiest way is to call math.randomseed(os.time()) at the beginning of your program.
Efficiency; is this the best way to do it?
Depends. For what you seem to want, yes, it's definitely efficient enough. If anything, I'd change it to the following to avoid magic numbers which will make it harder to understand the code in the future.
--- etc.
local mapData = {
map = maps[math.random(#maps)],
mode = gameModes[math.random(#gameModes)]
}
-- etc.
print(a.map, a.mode)
And remember:
Premature optimization is the root of all evil.
— Donald Knuth
You did very good by creating a separate function for generating your modes and maps. This separates code and is modular and neat.
Now, you have your game modes in a table modes = {} (=which is basically a list of strings).
And you have your maps in another table maps = {}.
Each of the table items has a key, that, when omitted, becomes a number counted upwards. In your case, there are 3 items in modes and 3 items in maps, so keys would be 1, 2, 3. The key is used to grab a certain item in that table (=list). E.g. maps[2] would grab the second item in the maps table, whose value is map 2. Same applies to the modes table. Hence your output you asked about.
To get a random game mode, you just call math.random(#mode). math.random can accept up to two parameters. With these you define your range, to pick the random number from. You can also pass a single parameter, then Lua assumes to you want to start at 1. So math.random(3) becomes actually math.random(1, 3). #mode in this case stand for "count all game modes in that table and give me that count" which is 3.
To return your chosen map and game mode from that function we could use another table, just to hold both values. This time however the table would have different keys to access the values inside it; namely "map" and "mode".
Complete example would be:
local function setupRound()
local modes = {"mode 1", "mode 2", "mode 3"} -- different game modes
local maps = {"map 1", "map 2", "map 3"} -- different maps
return {map = maps[math.random(#maps)], mode = modes[math.random(#modes)]}
end
for i = 1, 10 do
local freshRound = setupRound()
print(freshRound.map, freshRound.mode)
end

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

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.

Resources