How to fix syntax Roblox Lua - lua

I kept getting error, but its seems already good at if and elseif statements, kept giving me last line error
How the code works? When chat :example it does do ..., You can check under below, also this code for exploit in game, help me to fix some error syntax
Code :
local players = game:GetService("Players")
local localPlayer = players.LocalPlayer
localPlayer.Chatted:connect(function(cht)
if cht:match(":kill all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":explode "..player.Name.."")
print("Successfully Killed " .. player.Name .. ".")
end
end
elseif cht:match(":explode all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":explode "..player.Name.."")
print("Successfully Exploded " .. player.Name .. ".")
end
end
elseif cht:match(":freeze all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":freeze "..player.Name.."")
print("Successfully Froze " .. player.Name .. ".")
end
end
elseif cht:match(":jail all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":jail "..player.Name.."")
print("Successfully Jailed " .. player.Name .. ".")
end
end
elseif cht:match(":floppa all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":floppa "..player.Name.."")
print("Successfully Killed " .. player.Name .. ".")
end
end
elseif cht:match(":wednesday all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":wednesday "..player.Name.."")
print("Successfully Transformed " .. player.Name .. " Into Wednesday.")
end
end
elseif cht:match(":void all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":void "..player.Name.."")
print("Successfully Transformed " .. player.Name .. " Into Void.")
end
end
elseif cht:match(":ff all") or cht:match(":forcefield all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":ff "..player.Name.."")
print("Successfully Forcefielded " .. player.Name .. ".")
end
end
elseif cht:match(":god all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":god "..player.Name.."")
print("Successfully Made god mode to "..player.Name.."")
elseif cht:match(":unff all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":unff "..player.Name.."")
print("Successfully Disabled Forcefield " .. player.Name .. ".")
end
end
elseif cht:match(":unjail all") then
for _, player in pairs(players:GetPlayers()) do
game.Players:Chat(":unjail all "..player.Name.."")
print("Successfully Unjailed " .. player.Name .. ".")
wait(0.2)
end
elseif cht:match(":ungod all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":ungod "..player.Name.."")
print("Successfully Disabled God Mode " .. player.Name .. ".")
end
end
elseif cht:match(":disco all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":disco "..player.Name.."")
print("Successfully Set Disco Mode for " .. player.Name .. ".")
end
end
end
end
end
)
I keep trying to fix it by console in Roblox /console, really following what it's do, and yeah, struggling

Try this :
local players = game:GetService("Players")
local localPlayer = players.LocalPlayer
localPlayer.Chatted:connect(function(cht)
if cht:match(":kill all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":explode "..player.Name.."")
print("Successfully Killed " .. player.Name .. ".")
end
end
elseif cht:match(":explode all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":explode "..player.Name.."")
print("Successfully Exploded " .. player.Name .. ".")
end
end
elseif cht:match(":freeze all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":freeze "..player.Name.."")
print("Successfully Froze " .. player.Name .. ".")
end
end
elseif cht:match(":jail all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":jail "..player.Name.."")
print("Successfully Jailed " .. player.Name .. ".")
end
end
elseif cht:match(":floppa all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":floppa "..player.Name.."")
print("Successfully Killed " .. player.Name .. ".")
end
end
elseif cht:match(":wednesday all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":wednesday "..player.Name.."")
print("Successfully Transformed " .. player.Name .. " Into Wednesday.")
end
end
elseif cht:match(":void all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":void "..player.Name.."")
print("Successfully Transformed " .. player.Name .. " Into Void.")
end
end
elseif cht:match(":ff all") or cht:match(":forcefield all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":ff "..player.Name.."")
print("Successfully Forcefielded " .. player.Name .. ".")
end
end
elseif cht:match(":god all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":god "..player.Name.."")
print("Successfully Made god mode to "..player.Name.."")
elseif cht:match(":unff all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":unff "..player.Name.."")
print("Successfully Disabled Forcefield " .. player.Name .. ".")
end
end
end
elseif cht:match(":unjail all") then
for _, player in pairs(players:GetPlayers()) do
game.Players:Chat(":unjail all "..player.Name.."")
print("Successfully Unjailed " .. player.Name .. ".")
wait(0.2)
end
elseif cht:match(":ungod all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":ungod "..player.Name.."")
print("Successfully Disabled God Mode " .. player.Name .. ".")
end
end
elseif cht:match(":disco all") then
for _, player in pairs(players:GetPlayers()) do
if player ~= localPlayer then
game.Players:Chat(":disco "..player.Name.."")
print("Successfully Set Disco Mode for " .. player.Name .. ".")
end
end
end
end)
U haded some messed up end statements at ur code.
This shoulder probably work now.

Related

found out of script not updating - roblox lua

I am trying to make it so the GUI updates every time a player collects an item to show how many items they have collected. it works very well, but it only updates when the player leaves and rejoins. Any ideas??
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local catscollected = player:WaitForChild("catsCollected")
Cats_Found_Out_Of = 0
if catscollected:FindFirstChild("sleeping cat") then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
if catscollected:FindFirstChild("fire cat") then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
end
end
while true do
script.Parent.Text = Cats_Found_Out_Of.." / 3 Found"
end
It is because of not putting an if statement into the while loop.
Explanation:
Don't use while true do, instead of this use while wait(0.1) do so it will not lag the whole game on client side
It will run only on join and leave because you haven't put the if statement into the while loop. You can either change it to the function or put into the while loop as a code.
Your code should now look like this:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local catscollected = player:WaitForChild("catsCollected")
while wait(0.1) do
Cats_Found_Out_Of = 0
for _, v in pairs(catscollected:GetChildren()) do
if v.Name == "sleeping cat" or v.Name == "fire cat" then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
end
end
script.Parent.Text = Cats_Found_Out_Of.." / 3 Found"
end

Trying to create a minimax algorithm for a tic tac toe game, but I keep getting an nil value in a for loop

I have made a post a few days ago, about trying to make a minimax algorithm but I didn't understand it at the time and I got told to go slowly through the tutorial I was using and try to make sure I understood, that is what I am doing now, I am going through each piece of code and making sure it prints the correct values and make sure it actually works.
So the issue I am having with is this part of the code
local allTestPlayInfos = {}
for i = 1, size_of_array do
local currentTestPlayInfo = {}
local index = avaliable_slots[i]
board[index] = current_player
if current_player == "O" then
local x_result = minimax(board,"X")
currentTestPlayInfo["score"] = x_result["score"]
else
local o_result = minimax(board,"O")
currentTestPlayInfo["score"] = o_result["score"] --This line
board[index] = " "
currentTestPlayInfo["index"] = index
table.insert(allTestPlayInfos,i,currentTestPlayInfo)
end
_draw_board()
end
I am not sure why but at THIS LINE it keeps producing a nil value, that shouldnt be the case as the functions at the top should catch when the board becomes full but it doesnt, im not sure why, I have done everything else correctly to my knowladge, can someone give some in sight on why it keeps returning a nil value.
(https://www.freecodecamp.org/news/minimax-algorithm-guide-how-to-create-an-unbeatable-ai/)
Here is the full code, please copy and paste it and try it out.
local board_data = {top_L= " ", top_M = " ", top_R= " ", mid_L= " ", mid_M= " ", mid_R= " ", low_L= " ", low_M= " ",
low_R= " "}
local location = {"top","mid","low"}
local position = {"_L","_M","_R"}
local function _draw_board() -- Draws the games table
print(
board_data["top_L"].."┃"..board_data["top_M"].."┃"..board_data["top_R"].."\n"..
"------\n"..
board_data["mid_L"].."┃"..board_data["mid_M"].."┃"..board_data["mid_R"].."\n"..
"------\n"..
board_data["low_L"].."┃"..board_data["low_M"].."┃"..board_data["low_R"].."\n"
)
end
local function _check_if_position_exists_and_is_empty(_input) -- Checks if the user has entered a valid position and that it is empty
return board_data[_input] == " "
end
local function _check_win_condition(board,current_turn) --Checks if the current player has won
for i = 1, 3 do --Firstly checks each row
if board[location[i]..position[1]] == current_turn and board[location[i]..position[2]] == current_turn and board[location[i]..position[3]] == current_turn then
return true --Then checks columns
elseif board[location[1]..position[i]] == current_turn and board[location[2]..position[i]] == current_turn and board[location[3]..position[i]] == current_turn then
return true
end -- Then checks diagonals
if board[location[1]..position[1]] == current_turn and board[location[2]..position[2]] == current_turn and board[location[3]..position[3]] == current_turn then
return true
elseif board[location[3]..position[1]] == current_turn and board[location[2]..position[2]] == current_turn and board[location[1]..position[3]] == current_turn then
return true
end
end
end
local function check_tie_condition(array)
local is_not_empty = 0
for i = 1,3 do
if array[location[i]..position[1]] ~= " " and array[location[i]..position[2]] ~= " " and array[location[i]..position[3]] ~= " " then
is_not_empty = is_not_empty + 3
end
end
if is_not_empty == 9 then
return true
end
return false
end
local function get_array_size(array)
local count = 0
for i in pairs(array) do
count = count + 1
end
return count
end
local function find_empty_slots(board)
local key_array = {"top_L","top_M","top_R","mid_L","mid_M","mid_R","low_L","low_M","low_R"}
local empty_slots = {}
for a in pairs(key_array) do
if board[key_array[a]] == " " then
table.insert(empty_slots,key_array[a])
end
end
return empty_slots
end
local function minimax(board,current_player) -- MINIMAX ai
local avaliable_slots = find_empty_slots(board)
local size_of_array = get_array_size(avaliable_slots)
if _check_win_condition(board,"X") then
return {score = -1}
elseif _check_win_condition(board,"O") then
return {score = 1}
elseif check_tie_condition(board) then
return {score = 0}
end
local allTestPlayInfos = {}
for i = 1, size_of_array do
local currentTestPlayInfo = {}
local index = avaliable_slots[i]
board[index] = current_player
if current_player == "O" then
local x_result = minimax(board,"X")
currentTestPlayInfo["score"] = x_result["score"]
else
local o_result = minimax(board,"O")
currentTestPlayInfo["score"] = o_result["score"] --This line
board[index] = " "
currentTestPlayInfo["index"] = index
table.insert(allTestPlayInfos,i,currentTestPlayInfo)
end
_draw_board()
end
local bestTestPlay = {}
if current_player == "O" then
local best_score = -700
for i = 1, get_array_size(allTestPlayInfos) do
if allTestPlayInfos[i]["score"] > best_score then
best_score = allTestPlayInfos[i]["score"]
bestTestPlay = i --allTestPlayInfos[i]["index"]
else
local best_score = 700
for i = 1, get_array_size(allTestPlayInfos) do
if allTestPlayInfos[i]["score"] < best_score then
best_score = allTestPlayInfos[i]["score"]
bestTestPlay = i --allTestPlayInfos[i]["index"]
end
end
end
end
end
return allTestPlayInfos[bestTestPlay]
end
local function _game() --The main loop of the game
local current_turn = "O" -- it holds two states X or O
print("Please select a position from the board, to access the top row, type top_position position being L, M , R e.g top_L \n")
_draw_board()
while true do
print("Player " ..current_turn.. " is selected!")
if current_turn == "O" then -- Checks if its Os turn/AI and make it play the minimax function
local play = minimax(board_data,"O")
print(play)
break
--current_turn = "X"
else -- Else its the players turn
local Input = io.read()
if _check_if_position_exists_and_is_empty(Input) then
board_data[Input] = current_turn
_draw_board()
if _check_win_condition(board_data,current_turn) then
print("Player "..current_turn .. " Has won this game!")
break
elseif check_tie_condition(board_data) then
print("The game has ended at a tie!")
break
end
if current_turn == "X" then -- Switch to the other player
current_turn = "O"
elseif current_turn == "O" then
current_turn = "X"
end
else
print("\nThat wasnt a command in the table or the slot wasnt empty!, example top_L, mid_R, low_M \n")
end
end
end
end
_game()
edit:
local function minimax(board,current_player) -- MINIMAX ai
local avaliable_slots = find_empty_slots(board)
local size_of_array = get_array_size(avaliable_slots)
if _check_win_condition(board,"X") then
return {score = -1}
elseif _check_win_condition(board,"O") then
return {score = 1}
elseif check_tie_condition(board) then
return {score = 0}
end
local allTestPlayInfos = {}
for i = 1, size_of_array do
local currentTestPlayInfo = {}
local index = avaliable_slots[i]
board[index] = current_player
if current_player == "O" then
local x_result = minimax(board,"X")
currentTestPlayInfo["score"] = x_result["score"]
else
local o_result = minimax(board,"O")
currentTestPlayInfo["score"] = o_result["score"] --This line
board[index] = " "
currentTestPlayInfo["index"] = index
table.insert(allTestPlayInfos,i,currentTestPlayInfo)
end
end
local bestTestPlay = {}
if current_player == "O" then
local best_score = -700
for i = 1, get_array_size(allTestPlayInfos) do
if allTestPlayInfos[i]["score"] > best_score then
best_score = allTestPlayInfos[i]["score"]
bestTestPlay = i --allTestPlayInfos[i]["index"]
end
end
else
local best_score = 700
for i = 1, get_array_size(allTestPlayInfos) do
if allTestPlayInfos[i]["score"] < best_score then
best_score = allTestPlayInfos[i]["score"]
bestTestPlay = i --allTestPlayInfos[i]["index"]
end
end
end
return allTestPlayInfos[bestTestPlay]
end
I have fixed the ends (at least I think I have) and I still have it going out of bounds producing a nil value and I am not sure why, can someone please guide me, I would be grateful!
for i = 1, size_of_array do
local currentTestPlayInfo = {}
local index = avaliable_slots[i]
_draw_board() --This shows the board with one empty slot
board[index] = current_player
print(check_tie_condition(board)) -- THis returns true because its full
_draw_board() -- draws the board and it is visually full as well
if current_player == "O" then
local x_result = minimax(board,"X") --This minimax function should be returning 0 since its full but it doesnt and I dont know why.
currentTestPlayInfo["score"] = x_result["score"]
else
local o_result = minimax(board,"O")
currentTestPlayInfo["score"] = o_result["score"] --Why does the score in the array get asigned a nil value it shouldnt be NIL!
board[index] = " "
currentTestPlayInfo["index"] = index
table.insert(allTestPlayInfos,i,currentTestPlayInfo)
end
This small bit of code is confusing me, the minimax reqursion doesnt return 0 since the board is full, why doesnt it return 0 like I told it to!
First thing I noticed is that you ask the player to pick a cell, but you start with the AI befor processing the players input.
Acutally debugging this is pretty trivial. All you need to do is to add a few debug prints where it makes sense.
I simply drew the board after each change and instantly noticed that you don't stop when the game is over.
You do not even stop when all cells are filled. This lead to an empty table available_slots. Then you return nil because the loop is not run. (I already told you this in your last post).
Which finally leads to indexing a nil value.
Edit:
I don't know why you keep mentioning that you move ends around. Your whole game logic is broken. Moving an end won't fix that.
This is what a few simple prints give you. Note how you ask the player for a turn but then let the AI begin...
Please select a position from the board, to access the top row, type top_position position being L, M , R e.g top_L
┃ ┃
------
┃ ┃
------
┃ ┃
Player O is selected!
called minimax, player O
size of array 9
┃ ┃
------
┃ ┃
------
┃ ┃
called minimax, player X
size of array 8
O┃ ┃
------
┃ ┃
------
┃ ┃
called minimax, player O
size of array 7
O┃X┃
------
┃ ┃
------
┃ ┃
called minimax, player X
size of array 6
O┃X┃O
------
┃ ┃
------
┃ ┃
called minimax, player O
size of array 5
O┃X┃O
------
X┃ ┃
------
┃ ┃
called minimax, player X
size of array 4
O┃X┃O
------
X┃O┃
------
┃ ┃
called minimax, player O
size of array 3
O┃X┃O
------
X┃O┃X
------
┃ ┃
called minimax, player X
size of array 2
O┃X┃O
------
X┃O┃X
------
O┃ ┃
O wins
called minimax, player X
size of array 1
O┃X┃O
------
X┃O┃X
------
O┃O┃
O wins
called minimax, player X
size of array 0
O┃X┃O
------
X┃O┃X
------
O┃O┃O
O wins
lua: main.lua:99: attempt to index a nil value (local 'o_result')
You play one test game, you successfully detect the win condition. But after that you still play two more turns. Why are you continuing to run the for loop after the game is over?
That is nonsense and leads to the observed error.

How to score when killing an NPC

When I kill an NPC, my score should increase, but it does not.
Here's my code. It is located under my NPC model.
local Humanoid = script.Parent.Humanoid
function PwntX_X()
local tag = Humanoid:findFirstChild("creator")
if tag ~= nil then
if tag.Value ~= nil then
local Leaderstats = tag.Value:findFirstChild("leaderstats")
if Leaderstats ~= nil then
Leaderstats.Score.Value = Leaderstats.Score.Value + 250 --Change Money to the stat that is increased.
wait(0.1)
script:remove()
end
end
end
end
Humanoid.Died:connect(PwntX_X)
And here's my code for the leaderboard
game.Players.PlayerAdded:Connect(function(plr)
local stats = Instance.new("BoolValue",plr)
stats.Name = "leaderstats"
local score = Instance.new("IntValue", stats)
score.Name = "Score"
score.Value = 0
end)
Not sure, but looks like
score.Value = Leaderstats.Score.Value

Why does it keep telling me attempt to index nil with 'wins'?

I have it so it loops through the players to check who's alive or not.
local function checkAlive()
local Player = game.Players:FindFirstChild("leaderstats")
for i,v in pairs(game.Players:GetChildren()) do
if v.Character then
if v.Character.Humanoid.Health > 0 then
Player.wins.Value = Player.wins.Value + 1
end
end
end
But it keeps telling me attempt to index nil with 'wins'?
local Player = game:GetService("Players")
local function checkAlive()
for i,v in pairs(Player:GetPlayers()) do
local leaderstats = v:FindFirstChild("leaderstats")
if v.Character then
if v.Character.Humanoid.Health > 0 then
Player.wins.Value = Player.wins.Value + 1
end
end
end
end

Why NodeMCU crashes with no error after boot with this code?

My ESP8266 keeps restarting.
This is my init.lua:
cfg={}
cfg.ssid="Sensor"
cfg.auth=AUTH_OPEN
wifi.ap.config(cfg)
wifi.setmode(wifi.STATION)
wifi.sta.getap(function(t)
available_aps = ""
if t then
for k,v in pairs(t) do
ap = string.format("%-10s",k)
ap = trim(ap)
available_aps = available_aps .. "<option value='".. ap .."'>".. ap .."</option>"
end
setup_server(available_aps)
end
end)
function setup_server(aps)
wifi.setmode(wifi.SOFTAP)
srv=net.createServer(net.TCP)
srv:listen(80,function(client)
client:on("receive",function(client,request)
wifi.sta.getap(function(t)
available_aps = ""
if t then
for k,v in pairs(t) do
ap = string.format("%-10s",k)
ap = trim(ap)
available_aps = available_aps .. "<option value='".. ap .."'>".. ap .."</option>"
end
end
end)
local buf = "";
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf = "<html><body>"
buf = buf .. "<h3>Config</h3><br>"
buf = buf .. "<form method='get' action='http://" .. wifi.ap.getip() .."'>"
buf = buf .. "Select access point: <select name='ap'>" .. available_aps .. "</select><br>"
buf = buf .. "Enter wifi password: <input type='password' name='psw'></input><br>"
buf = buf .. "Server-IP: <input name='ipTCP' value='192.168.178.1'></input><br>"
buf = buf .. "<br><button type='submit'>Save</button>"
buf = buf .. "</form></body></html>"
local _on,_off = "",""
if(_GET.pin == "ON1")then
buf = buf.."NICE";
elseif(_GET.pin == "OFF1")then
gpio.write(led1, gpio.LOW);
elseif(_GET.pin == "ON2")then
gpio.write(led2, gpio.HIGH);
elseif(_GET.pin == "OFF2")then
gpio.write(led2, gpio.LOW);
end
client:send(buf);
client:close();
collectgarbage();
end)
end)
end
Why it crashes every time after reboot?
How can I troubleshoot this?
I have NodeMCU 0.9.5 build 20150318 powered by Lua 5.1.4.
Another lua scripts are running ok.
I have the same function within client:on("receive",function(client,request).
It's not supposed to be here.
I didn't see a call to wifi.sta.connect()
Strings are immutable so each time you reassign buf, you create a new one. Yes the GC will clean it up, if you don't run out first.
You can't call client:send() and client:close() back to back... well, you can but it won't work very well. I'd also worry about sending all of that in one call.
Even though they don't accept callbacks the wifi config and connect routines do need to run asynchronously, call them with a timer, then check status before continuing.
The first item is a show-stopper, the others may cause outright failure or may be intermittent.

Resources