Adding objects to group in loop in Lua - lua

So I want to add my coin object to my gameGroup via a loop,instead of adding each one manually line by line
What I'm trying to do now clearly would not work because you can't add a string to group of objects
Is there a way to do this?
local coin1 = getCoin(6000,500)
local coin2 = getCoin(850,550)
local coin3 = getCoin(980,550)
local coin4 = getCoin(1900,550)
local coin5 = getCoin(2850,380)
local coin6 = getCoin(3199,486)
local coin7 = getCoin(3543,455)
local coin8 = getCoin(3780,380)
local coinOverlay1 = display.newRect( 850,550,80,80 )
physics.addBody( coinOverlay1, { bounce=0 } )
coinOverlay1.isVisible = false
gameGroup:insert(coinOverlay1)
sceneGroup:insert( coinGroup )
coinGroup:insert( coin1 ) -- Not this would take up too many lines for each coin,there will be over 40 coins
coinGroup:insert(coin2)
camera:add( coinGroup, 1 )
for i=1,8 do
local test_1 = "coin"
local test_2 = i
local test_3 = "coin"..test_2
print (test_3)
coinGroup:insert(test_3)
end

something like this?
coins = {
{6000,500},
{850,550},
{980,550},
{1900,550},
{2850,380},
{3199,486},
{3543,455},
{3780,380}
}
for i,v in ipairs(coins) do
coinGroup:insert(getCoin(v[1],v[2]))
end

Related

How to a team system ? (Roblox)

im trying to make a tag game that one player from the spectate team or nutural team will be chosen to be the tag and another will be chosen to be the runner. They'll both teleport to a small map, there the tag will have to try catch the runner before the times up.
Now my problem is that when the player loads to the game he does'nt autoassigned to the nuturalteam(spectateteam) and also when the players tp to the map they wont change the teams to a tager and runner they'll both be in the same team. Help will be appriciated!
Also i dont get any errors in the outpot besides "loadstring is not availble".
Here is the round system script:
Teams = game:GetService("Teams")
local SpectateTeam = game.Teams.Spectate
local ItTeam = game.Teams.It
local RunnerTeam = game.Teams.Runner
local roundlength = 5
local intermissionLength = 4
local inRound = game.ReplicatedStorage.InRound
local Status = game.ReplicatedStorage.Status
local LobbySpawn = workspace.Map.SpawnLobby
local MapSpawnIt = workspace.Map.SpawnMapIt
local MapSpawnRunner = workspace.Map.SpawnMapRunner
local frame = game.StarterGui.ScreenGuimenu.Frame
local KillerSpawn = workspace.Map.SpawnMapIt
local lobbyspace = workspace.Lobbyspace
game.Players.PlayerAdded:Connect(function(player)
player.Team = SpectateTeam
end)
inRound.Changed:Connect(function(player)
if inRound.Value == true then
local chosen = Players:GetChildren()[math.random(1, #Players:GetChildren())]
print(" is It")
chosen.Team = ItTeam
local runner = SpectateTeam:GetPlayers()[math.random(1, #Players:GetChildren())]
print(" is Runner")
runner.Team = Teams.Runner
wait()
runner.Character.HumanoidRootPart.CFrame = MapSpawnRunner.CFrame
chosen.Character.HumanoidRootPart.CFrame = KillerSpawn.CFrame
end
if inRound.Value == false then
for _, player in pairs(game.Players:GetChildren(player)) do
local char = player.Character
char.HumanoidRootPart.CFrame = LobbySpawn.CFrame
player.Team = SpectateTeam
end
end
end)
local function RoundTimer()
while wait() do
for i = intermissionLength, 0, -1 do
inRound.Value = false
wait(1)
Status.Value = "Intermission:" .. i .."seconds left!"
end
for i = roundlength, 0, -1 do
inRound.Value = true
wait(1)
Status.Value = "Game:" .. i .."seconds left!"
end
end
end
spawn(RoundTimer) ```
I found the answer! i just forgot to sync the color of the teams with the spawns :)

Unable to assign property Text. string expected, got nil roblox error

I have no idea how this is an error, can anyone help me out? This is supposed to be a global leaderboard, but nope, this error is ruining it. The line is new.ClickVal.Text = val. it used to be new.Value.Text = val, and i thought maybe it was because the game thought 'Value' was the actual VALUE of the text, which it was the name of a textlabel, so i changed it to 'ClickVal" and it still doesnt work. Thank you for helping out!!!
local sg = script.Parent
local sample = script:WaitForChild("Sample")
local sf = sg:WaitForChild("ScrollingFrame")
local ui = sf:WaitForChild("UI")
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetOrderedDataStore("Leaderboard")
wait(10)
while true do
for i,plr in pairs(game.Players:GetChildren()) do
if plr.UserId>0 then
local ps = game:GetService("PointsService")
local w = plr.leaderstats.Clicks.Value
if w then
pcall(function()
dataStore:UpdateAsync(plr.UserId,function(oldVal)
return tonumber(w)
end)
end)
end
end
end
local smallestFirst = false
local numberToShow = 100
local minValue = 1
local maxValue = 10e100
local pages = dataStore:GetSortedAsync(smallestFirst, numberToShow, minValue, maxValue)
local top = pages:GetCurrentPage()
local data = {}
for a,b in ipairs(top) do
local userId = b.key
local points = b.Value
local username = "[Failed To Load]"
local s,e = pcall(function()
username = game.Players:GetNameFromUserIdAsync(userId)
end)
if not s then
warn("Error getting name for "..userId..". Error: "..e)
end
local image = game.Players:GetUserThumbnailAsync(userId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size150x150)
table.insert(data,{username,points,image})
end
ui.Parent = script
sf:ClearAllChildren()
ui.Parent = sf
for number,d in pairs(data) do
local name = d[1]
local val = d[2]
local image = d[3]
local color = Color3.new(1,1,1)
if number == 1 then
color = Color3.new(1,1,0)
elseif number == 2 then
color = Color3.new(0.7,0.7,0.7)
elseif number == 3 then
color = Color3.fromRGB(166, 112, 0)
end
local new = sample:Clone()
new.Name = name
new.LayoutOrder = number
new.Image.Image = image
new.Image.Place.Text = number
new.Image.Place.TextColor3 = color
new.PName.Text = name
new.ClickVal.Text = val
new.ClickVal.TextColor3 = color
new.PName.TextColor3 = color
new.Parent = sf
end
wait()
sf.CanvasSize = UDim2.new(0,0,0,ui.AbsoluteContentSize.Y)
wait(10)
end
if you have the fix then post it please thanks!

How can I fix the data in roblox

I asked a second question because my last one was getting out of the subject with comments. So I'm trying to make roblox saving the stats of a player but it puts always the basic stats. Even if the player already played.
Here's my code :
local HttpService = game:GetService("HttpService")
local DataStoreService = game:GetService("DataStoreService")
local ds = DataStoreService:GetDataStore("Data")
game.Players.PlayerAdded:Connect(function(player)
local defaultData = {
coins = 0,
gems = 0,
xp = 0,
level = 1,
maxstamina = 100,
maxmagic = 100,
}
local loadedData = defaultData
local success, result = pcall(function()
return ds:GetAsync(player.UserId)
end)
if success then
if result then
-- if we've successfully loaded the data, parse the stored json data
print(string.format("An old player named %s has returned with data : %s!", player.Name, tostring(result)))
-- player data should look like this :
-- {"coins":0,"xp":0,"gems":0,"level":1,"maxstamina":100,"maxmagic":100}
local parseSuccess, parseResult = pcall(function()
return HttpService:JSONDecode(result)
end)
if parseSuccess then
loadedData = parseResult
else
warn(string.format("Failed to parse %s with error : %s", tostring(result), tostring(parseResult)))
end
else
-- we have a new player
print(string.format("New player named %s has joined!", player.Name))
end
else
warn(string.format("Something went wrong fetching %s's data : %s", player.Name, tostring(result)))
-- TO DO: FIGURE OUT HOW YOU WANT TO HANDLE THIS ERROR.
-- IF YOU DO NOTHING, THE PLAYER'S DATA WILL BE THE DEFAULT DATA USED FOR
-- NEW PLAYERS
end
-- create the leaderstats and hidden values, load the data from the loadedData table
local leaderstats = Instance.new("Model", player)
leaderstats.Name = "leaderstats"
local hidden = Instance.new("Model", player)
hidden.Name = "hidden"
local coins = Instance.new("IntValue", leaderstats)
coins.Name = "Coins"
coins.Value = loadedData.coins
local gems = Instance.new("IntValue", leaderstats)
gems.Name = "Gems"
gems.Value = loadedData.gems
local level = Instance.new("IntValue", leaderstats)
level.Name = "Level"
level.Value = loadedData.level
local xp = Instance.new("IntValue", hidden)
xp.Name = "XP"
xp.Value = loadedData.xp
local maxstamina = Instance.new("IntValue", hidden)
maxstamina.Name = "MaxStamina"
maxstamina.Value = loadedData.maxstamina
local maxmagic = Instance.new("IntValue", hidden)
maxmagic.Name = "MaxMagic"
maxmagic.Value = loadedData.maxmagic
local stamina = Instance.new("IntValue", hidden)
stamina.Name = "Stamina"
stamina.Value = loadedData.maxstamina
local magic = Instance.new("IntValue", hidden)
magic.Name = "Magic"
magic.Value = loadedData.maxmagic
end)
game.Players.PlayerRemoving:Connect(function(player)
local stats = player.leaderstats
local hidden = player.hidden
local data = {
coins = stats.Coins.Value,
gems = stats.Gems.Value,
xp = hidden.XP.Value,
level = stats.Level.Value,
maxstamina = hidden.MaxStamina.Value,
maxmagic = hidden.MaxMagic.Value,
}
-- wrap the request in a try-catch block to ensure that failures don't throw errors
local success, result = pcall(function()
-- save all the data as a JSON string
ds:setAsync(player.UserId, HttpService:JSONEncode(data))
end)
if not success then
warn(string.format("Failed to save %s's data with error : %s", player.Name, tostring(result)))
-- TO DO: FIGURE OUT HOW YOU WANT TO HANDLE THIS ERROR.
-- IF YOU DO NOTHING, THE PLAYER WILL LOSE THIS SESSION'S DATA
end
end)
More info :
The game is public but not finished here's the link if you wan't to test it : https://web.roblox.com/games/4867142155/Medieval-Fighting-Simulator-Beta?refPageId=b25ecb6b-40c9-4c28-a4bb-2e4e0a6c6d61
The Studio API Service is enabled
There's no error code
How can you help me?
I changed my answer :
So we must use DataStore2 and then it shall work!
Here's a good DataStore2 tutorial : https://www.youtube.com/watch?v=hBfMfB0BwGA
Here's my final code :
local DataStore2 = require(1936396537)
local defaultCoins = 0
local defaultGems = 0
local defaultLevel = 1
local defaultXP = 0
local defaultMStamina = 100
local defaultMMagic = 100
DataStore2.Combine("Data","coins","gems","level","xp","mstamina","mmagic")
local xpToLevelUp = function(level)
return 100 + level * 5
end
game.Players.PlayerAdded:Connect(function(player)
local coinsDataStore = DataStore2("coins",player)
local gemsDataStore = DataStore2("gems",player)
local levelDataStore = DataStore2("level",player)
local xpDataStore = DataStore2("xp",player)
local mstaminaDataStore = DataStore2("mstamina",player)
local mmagicDataStore = DataStore2("mmagic",player)
local stats = Instance.new("Folder",player)
stats.Name = "stats"
local coins = Instance.new("IntValue",stats)
coins.Name = "Coins"
local gems = Instance.new("IntValue",stats)
gems.Name = "Gems"
local level = Instance.new("IntValue",stats)
level.Name = "Level"
local xp = Instance.new("IntValue",stats)
xp.Name = "XP"
local mstamina = Instance.new("IntValue",stats)
mstamina.Name = "MStamina"
local stamina = Instance.new("IntValue",stats)
stamina.Name = "Stamina"
local mmagic = Instance.new("IntValue",stats)
mmagic.Name = "MMagic"
local magic = Instance.new("IntValue",stats)
magic.Name = "Magic"
local function coinsUpdate(updatedValue)
coins.Value = coinsDataStore:Get(updatedValue)
end
local function gemsUpdate(updatedValue)
gems.Value = gemsDataStore:Get(updatedValue)
end
local function levelUpdate(updatedValue)
level.Value = levelDataStore:Get(updatedValue)
end
local function xpUpdate(updatedValue)
if updatedValue >= xpToLevelUp(levelDataStore:Get(defaultLevel)) then
xpDataStore:Increment(xpToLevelUp(levelDataStore:Get(defaultLevel)) * -1)
levelDataStore:Increment(1)
else
player.stats.XP.Value = updatedValue
end
end
local function mStaminaUpdate(updatedValue)
mstamina.Value = mstaminaDataStore:Get(updatedValue)
end
local function mMagicUpdate(updatedValue)
mmagic.Value = mmagicDataStore:Get(updatedValue)
end
coinsUpdate(defaultCoins)
gemsUpdate(defaultGems)
levelUpdate(defaultLevel)
xpUpdate(defaultXP)
mStaminaUpdate(defaultMStamina)
mMagicUpdate(defaultMMagic)
stamina.Value = mstamina.Value
magic.Value = mmagic.Value
coinsDataStore:OnUpdate(coinsUpdate)
gemsDataStore:OnUpdate(gemsUpdate)
levelDataStore:OnUpdate(levelUpdate)
xpDataStore:OnUpdate(xpUpdate)
mstaminaDataStore:OnUpdate(mStaminaUpdate)
mmagicDataStore:OnUpdate(mMagicUpdate)
end)
game.ReplicatedStorage.Buy.OnServerEvent:Connect(function(player,cost,item)
local coinsDataStore = DataStore2("coins",player)
if player.leaderstats.Coins.Value < cost then
game.ReplicatedStorage.NotEnoughCoins:FireClient(player)
else
coinsDataStore:Increment(cost * -1,defaultCoins)
local buyedItem = game.ReplicatedStorage.Products:WaitForChild(item)
local clonedItem = buyedItem:Clone()
clonedItem.Parent = player.Backpack
end
end)
game.ReplicatedStorage.EarnCoins.OnServerEvent:Connect(function(player,coins)
local coinsDataStore = DataStore2("coins",player)
coinsDataStore:Increment(coins,defaultCoins)
end)
game.ReplicatedStorage.EarnGems.OnServerEvent:Connect(function(player,gems)
local gemsDataStore = DataStore2("gems",player)
gemsDataStore:Increment(gems,defaultGems)
end)
game.ReplicatedStorage.Enchance.OnServerEvent:Connect(function(player,cost,item,enchancedItem)
local gemsDataStore = DataStore2("gems",player)
if player.leaderstats.Gems.Value < cost then
game.ReplicatedStorage.NotEnoughGems:FireClient(player)
else
gemsDataStore:Increment(cost * -1,defaultGems)
item:Destroy()
local clonedItem = enchancedItem:Clone()
clonedItem.Parent = player.Backpack
end
end)
game.ReplicatedStorage.GainXP.OnServerEvent:Connect(function(player,amount)
local xpDataStore = DataStore2("xp",player)
xpDataStore:Increment(amount,defaultXP)
end)
game.ReplicatedStorage.LevelUp.OnServerEvent:Connect(function(player)
local mstaminaDataStore = DataStore2("mstamina",player)
local mmagicDataStore = DataStore2("mmagic",player)
mstaminaDataStore:Increment(25,defaultMStamina)
mmagicDataStore:Increment(25,defaultMMagic)
end)

How to remove a number from a table?

I have no idea why this is not working. I am trying to delete the numbers in the table one by one (the randomCheck picks a number from the table and I want to delete that exact number) when I press the button 'MyButton'
math.randomseed(os.time())
_X = display.contentCenterX
_Y=display.contentCenterY
local numbers = {1,2,3,4,5,6,7,8,9,10}
local randomCheck = numbers[ math.random( #numbers) ]
local text = display.newText(""..randomCheck.."",_X,_Y,"Helvetica",50)
function removeNumber()
for i = 1, 10 do
if(randomCheck == i ) then
table.remove(numbers,i)
text.text = (""..i.."")
end
end
end
myButton = display.newRect(_X,_Y+100,100,80 )
myButton:addEventListener("tap", removeNumber)
In your loop, instead of
if(randomCheck == i)
use
if(randomCheck == numbers[i])
But all of that work is really unnecessary.
Instead of
local randomCheck = numbers[math.random( #numbers)]
use
local randomIndex = math.random(#numbers)
local randomCheck = numbers[randomIndex]
Then you can just
table.remove(numbers, randomIndex)

Corona SDK: Displaying Word from Table

OK my first question was too vague so I'm going to start simple here. I am trying to get a random word from a table in another lua file (content.lua). I have gotten the code to run without errors but cannot get a word to display on the screen or via print in the command console. What am I missing?
game.lua
--lua for game
--Loading the local variables
--creates the storyboard variable and calls the storyboard api
local storyboard = require ("storyboard")
--calls the mydata.lua module
local myData = require( "mydata" )
--calls the sfx.lua where sounds are stored
local sfx = require( "sfx" )
--calls the operations.lua
local operations = require("operations")
local content = require("content")
local playOrder
local wordGraphic
local currQuestion = 1
local homeButton
--tells storyboard to create a new scene
local scene = storyboard.newScene()
function scene:createScene(event)
local gameScreen = self.view
--creates a transparent background image centered on the display
local gameBackground = display.newImage("images/graphics/jungle1.jpg")
gameBackground.x = display.contentWidth/2
gameBackground.y = display.contentHeight/2
gameScreen:insert(gameBackground)
homeButton = display.newImage("images/buttons/home.png")
homeButton.alpha = .8
homeButton.y = 70
gameScreen:insert(homeButton)
playOrder = operations.getRandomOrder(#content)
end
local function onHomeTouch(event)
if event.phase == "began" then
storyboard.gotoScene("start")
end
end
function scene:enterScene(event)
homeButton:addEventListener("touch", onHomeTouch)
audio.play(sfx.Bkgd)
--uses the operations.lua to get words in a random order from the content.lua
--shows a random word from the content.lua table
function showWord()
local word = content[playOrder[currQuestion]].word
print(word)
wordGraphic = self.view
wordGraphic:insert(word)
wordGraphic.x = display.contentWidth/2
wordGraphic.y = display.contentHeight/2
end
end
--next question function which clears the screen and loads a new random word
function scene:exitScene(event)
homeButton:removeEventListener("touch", onHomeTouch)
end
function scene:destroyScene(event)
end
--the actual event listeners that make the functions work
scene:addEventListener("createScene", scene)
scene:addEventListener("enterScene", scene)
scene:addEventListener("exitScene", scene)
scene:addEventListener("destroyScene", scene)
return scene
Here is the operations.lua that gets the random order function
--operations.lua
module(..., package.seeall)
--function to get a random piece of data
function getRandomOrder(amount)
local order ={}
local i
local temp
local temp1
for n = 1,amount do
order[n] = n
end
for i=0,9 do
for temp = 1,amount do
n = math.random(1, amount)
temp1 = order[temp]
order[temp] = order[n]
order[n] = temp1
end
end
return order
end
This is where the words I am attempting to display are stored. I did not include all of them.
--content.lua
return {
{
id = "after",
word = "after"
},
{
id = "again",
word = "again"
},
{
id = "an",
word = "an"
},
{
id = "any",
word = "any"
},
{
id = "ask",
word = "ask"
},
{
id = "as",
word = "as"
},
{
id = "by",
word = "by"
}
}
You're not calling showWord in any of the code that you've shown so far. This is probably why it isn't even printing to the console. The function is just contained within scene:enterScene and exits to the outer scope, defining itself as a global variable when enterScene is called.

Resources