So I have been coding a nextbot in Gmod for a while now and have found a bug that causes Gmod to crash every time the function is run. here is the function:
function ENT:RecomputeTargetPath(path_target)
if self.testmode then
PrintMessage(HUD_PRINTTALK, 'recomputing target path')
end
self.path = Path("Chase")
if (CurTime() - self.LastPathingInfraction < 5) then
return
end
local targetPos = path_target:GetPos()
-- Run toward the position below the ENTity we're targetting, since we can't fly.
trace.start = targetPos
trace.filter = self:GetEnemy()
local tr = util.TraceEntity(trace, self:GetEnemy())
-- Of course, we sure that there IS a "below the target."
if (tr.Hit and util.IsInWorld(tr.HitPos)) then
targetPos = tr.HitPos
end
local rTime = SysTime()
self.path:Compute(self, targetPos)
if (SysTime() - rTime > 0.005) then
self.LastPathingInfraction = CurTime()
end
end
When this function is run, it recomputes the target path for the nextbot to make it move differently.
It's used in the context of an if that looks like this or something very close:
if (CurTime() - self.LastPathRecompute > 0.1) then
self.LastPathRecompute = CurTime()
self:RecomputeTargetPath(self:GetEnemy():GetPos())
end
As far as I know, all variables in the if are called before each.
As far as I know, all variables in the if are called before each.
I tried recalling them but that didn't work at all... I don't know what is happening.
Also, side note, the function gets called multiple times per second based on the player's movement.
I've also added debug prints to every line of the code to see where the issue was and the bug fixed itself when I added them but when I removed them the bug came back...
Any help?
Related
I am trying to make a part duplicate then delete the duplication script with the new part without deleting the script in the old part, this is in Roblox studio.
This is my code
local block = script.Parent
while true do
local xrange = math.random(-250,250)
local zrange = math.random(-250,250)
local item = block:Clone()
item.Parent = game.Workspace
item.Position = Vector3.new(xrange,.5,zrange)
item["Block Script"]:Destroy()
game.ReplicatedStorage.ItemCount.Value = game.ReplicatedStorage.ItemCount.Value + 1
wait(1)
end
The problem is that it runs as if it is supposed to duplicate 3 times for every loop and rather than creating 1 new part each second, it creates 3 parts. The main issue is that sometimes 1 of the 3 new parts won't have the other script that I have inside the parts, making the part a useless part that causes problems.
Does anyone see a problem?
You can also comment if you want more clarification.
If this is just an error or cannot be solved through the information given, I can probably work around but please comment if you need my clarification
Its duplicating 3 times because you are destroying the script last.. what you should try doing is:
1- creating a new folder on workspace ( going to call it "blocks" for example )
2- making the block and script of the block as the children of the "blocks" folder
3- and placing this code on the script:
local block = game.workspace."**blocks**".(Your part name)
while true do
local xrange = math.random(-250,250)
local zrange = math.random(-250,250)
local item = block:Clone()
item.Parent = game.Workspace
item.Position = Vector3.new(xrange,.5,zrange)
game.ReplicatedStorage.ItemCount.Value = game.ReplicatedStorage.ItemCount.Value + 1
wait(1)
end
If this does not work you can reply to this comment.
This code is for a modding engine, Unitale base on Unity Written in Lua
So I am trying to use a Boolean Variable in my script poseur.lua, so when certain conditions are met so I can pass it to the other script encounter.lua, where a engine Predefined functions is being uses to make actions happens base on the occurring moment.
I tried to read the engine documentation multiple times, follow the exact syntax of Lua's fonction like GetVar(), SetVar(), SetGobal(),GetGlobal().
Searching and google thing about the Language, post on the subreddit and Game Exchange and tried to solve it by myself for hours... I just can't do it and I can't understand why ?
I will show parts of my codes for each.
poseur:
-- A basic monster script skeleton you can copy and modify for your own creations.
comments = {"Smells like the work\rof an enemy stand.",
"Nidhogg_Warrior is posing like his\rlife depends on it.",
"Nidhogg_Warrior's limbs shouldn't\rbe moving in this way."}
commands = {"GREET", "JUMP", "FLIRT", "CRINGE"}
EndDialougue = {" ! ! !","ouiii"}
sprite = "poseur" --Always PNG. Extension is added automatically.
name = "Nidhogg_Warrior"
hp = 99
atk = 1
def = 1
check = "The Nidhogg_Warrior is\rsearching for the Nidhogg"
dialogbubble = "rightlarge" -- See documentation for what bubbles you have available.
canspare = false
cancheck = true
GreetCounter = 5
Berserk = false
encounter:
-- A basic encounter script skeleton you can copy and modify for your own creations.
encountertext = "Nidhogg_Warrior is\rrunning frantically"
nextwaves = {"bullettest_chaserorb"}
wavetimer = 5.0
arenasize = {155, 130}
music = "musAncientGuardian"
enemies = {"poseur"}
require("Monsters.poseur")
enemypositions = {{0, 0}}
-- A custom list with attacks to choose from.
-- Actual selection happens in EnemyDialogueEnding().
-- Put here in case you want to use it.
possible_attacks = {"bullettest_bouncy", "bullettest_chaserorb", "bullettest_touhou"}
function EncounterStarting()
-- If you want to change the game state immediately, this is the place.
Player.lv = 20
Player.hp = 99
Player.name = "Teemies"
poseur.GetVar("Berserk")
end
Thank you for reading.
The answer to my problem was to use SetGobal(), GetGobal().
For some reasons my previous attempt to simply use SetGobal()Resulted in nil value despite writing it like that SetGobal("Berserk",true) gave me a nill value error, as soon as I launch the game.
But I still used them wrong. First I needed to put it SetGobal() at the end of the condition instead of at the start of the the poseur.lua script because the change of value... for some reasons was being overwritten by it first installment.
And to test the variable in the function in my encounter.lua, I needed to write it like that
function EnemyDialogueStarting()
-- Good location for setting monster dialogue depending on how the battle is going.
if GetGlobal("Jimmies") == true then
TEEEST()
end
end
Also any tips an suggestions are still welcome !
Well firstly, in lua simple values like bool and number are copied on assignment:
global={}
a=2
global.a=a--this is a copy
a=4--this change won't affect value in table
print(global.a)--2
print(a)--4
Secondly,
SetGobal and the other mentioned functions are not part of lua language, they must be related to your engine. Probably, they use word 'Global' not as lua 'global' but in a sense defined by engine.
Depending on the engine specifics these functions might as well do a deep copy of any variable they're given (or might as well not work with complicated objects).
I'm trying to create a while true do loop, that reacts to clicks, using os.pullEvent, and also updates a monitor.
Problem being, it only updates the screen when I press one of the on screen buttons, and I've found out that's because pullEvent stops the script, until an event is fired.
Is it possible to make it so pullEvent doesn't stop me updating the monitor?
function getClick()
event,side,x,y = os.pullEvent("monitor_touch")
button.checkxy(x,y)
end
local tmp = 0;
while true do
button.label(2, 2, "Test "..tmp)
button.screen()
tmp++
getClick()
end
You can easily use the parallel api to run both codes essentially at the same time. How it works is it runs them in sequence until it hits something that uses os.pullEvent and then swaps over and does the other side, and if both stop at something that does os.pullEvent then it keeps swapping between until one yields and continues from there.
local function getClick()
local event,side,x,y = os.pullEvent("monitor_touch")
buttoncheckxy(x,y)
end
local tmp = 0
local function makeButtons()
while true do
button.label(2,2,"Test "..tmp)
button.screen()
tmp++
sleep(0)
end
end
parallel.waitForAny(getClick,makeButtons)
Now if you notice, first thing, I've made your while loop into a function and added a sleep inside it, so that it yields and allows the program to swap. At the end you see parallel.waitForAny() which runs the two functions that are specified and when one of them finishes, which in this case whenever you click on a button, then it ends. Notice however inside the arguments that I'm not calling the functions, I'm just passing them.
I don't have computercraft handy right now or look up the functions but i know that you can use the function os.startTimer(t) that will cause an event in t seconds (I think it is seconds)
usage:
update_rate = 1
local _timer = os.startTimer(update_rate)
while true do
local event = os.pullEvent()
if event == _timer then
--updte_screen()
_timer = os.startTimer(update_rate)
elseif event == --some oter events you want to take action for
--action()
end
end
note: the code is not tested and I didn't use computercraft in quite a while so pleas correct me if i did a mistake.
Having this error when I run my gamemode.
[ERROR]
gamemodes/rp/gamemode/cl_init.lua:910: attempt to index field 'Config' (a nil value)
1. unknown - gamemodes/rp/gamemode/cl_init.lua:910
config is a table, with index's such as config["Run Speed"] and the entire table is set globally equal to GM.Config in the sh_config.lua file. Why is config not being registered as a value? Must I include the config file into the cl_init file? and if so, how? Using the include()?
function GM:Think()
if ( self.Config["Local Voice"] ) then **--Referred line(910)**
for k, v in pairs( player.GetAll() ) do
if ( hook.Call("PlayerCanVoice",GAMEMODE, v) ) then
if ( v:IsMuted() ) then v:SetMuted(); end
else
if ( !v:IsMuted() ) then v:SetMuted(); end
end
end
end
-- Call the base class function.
return self.BaseClass:Think();
end
Edit -- config table in sh_config.lua.
local config = {};
-- Command
config["Command Prefix"] = "/"; -- The prefix that is used for chat commands.
config["Maximum Notes"] = 2; -- Maximum notes per player
config["Advert Cost"] = 60; -- The money that it costs to advertise.
config["Advert Timeout"] = 150 -- How many seconds between adverts
config["OOC Timeout"] = 60 -- How many seconds between OOC messages
config["Item Timer"] = 7 -- How many seconds between item uses
config["Item Timer (S)"] = 20 -- How many seconds between specific item uses
config["Note Fade Speed"] = 12 -- How many minutes before nots disappear
-- Voice
config["Local Voice"] = true; -- Players can only hear a player's voice if they are near them. This is the index being called which is creating an error.
config["Talk Radius"] = 256; -- The radius of each player that
--other players have to be in to hear them talk (units).
-- Player Stuff
config["Walk Speed"] = 150; -- The speed that players walk at.
config["Run Speed"] = 275; -- The speed that players run at.
GM.Config = config;
I have includecs("sh_config.lua"); in sh_init.lua. include("sh_config.lua") and AddCSLuaFile("sh_config.lua") in init.lua. and include("sh_config.lua"); in cl_init.lua.
Im still getting this stupid error though. Can someone explain what the difference between including and Addcs'ing a file does. How do I make sh_config's variables global in other files? Or in other words how do I make the desired file(cl_init) read through the code in sh_config.lua and I can use code from it in the client side init?
You need to include sh_config.lua at the top of cl_init.lua.
include("path/to/file.lua")
Be sure to do AddCSLuaFile("path/to/lua.lua") in the init.lua file as well. You will also need to do include("path/to/file.lua") in init.lua as well. (That's only required for shared files, though)
Also I am pretty sure the scope of your config table would be limited to sh_config.lua so you should remove local from your variable declaration.
*sh_config* is a shared file - Meaning it'll have to be included both clientside, and serverside.
In init.lua - In top of the other includes. Put include("sh_config.lua")
Also in init.lua, put AddCSLuaFile("sh_config.lua") - This will make sure the file is downloaded by the client, and executed clientside.
In cl_init.lua - put include("sh_config.lua"). Also around the other includes. This should work as expected.
Seeing how this is a Config file, I assume it should be included first, or almost first. It may contain vital settings, for the rest of the script load.
Also - Often a shared.lua is included, to be equal to a shared_init file. This may be your case. If it is, you should add one include("sh_config.lua") with the includes, in shared.lua, and AddCSLuaFile("sh_config.lua") in a if CLIENT then-block
I'm currently using giderous studio to make a tower defense game. However the code doesn't run as expected.
I made a function that make the monster in the game move according to the route settled in a JSON file. The move process go well EXCEPT the first monster being spawned firet, I have absolutely no ideas why the monster stop on its way. (As shown as diagram)
The following is my code:
level.lua:
level = Core.class(Sprite)
function level:init(levelId)
local level = dataSaver.load("level");
--load attributes
self.lives=level[tostring(levelId)]["lives"];
self.route=level[tostring(levelId)]["route"];
self.round=level[tostring(levelId)]["rounds"];
self.towersAllowed=level[tostring(levelId)]["towers"];
--some varibles
self.currentRound=1;
self.monsterList={};
end
function level:spawnMonster()
local monsterType=self.round[1]["type"];
local spawnNumber=self.round[1]["number"];
--set timer for spawn
local timer = Timer.new(self.round[1]["spawnInterval"],0);--spawnNumber);
timer:start();
--spawn
timer:addEventListener(Event.TIMER,function()
local spawnedMonster = monster.new(monsterType);
spawnedMonster.instance:setPosition(self.route[1]["x"],self.route[1]["y"]);
self:moveMonster(spawnedMonster);
end);
--after spawn finished, wait for next round.
timer:addEventListener(Event.TIMER_COMPLETE,function()
local nextRound = Timer.new(self.round[1]["timeUntilNextRound"],1);
nextRound:start();
nextRound:addEventListener(Event.TIMER_COMPLETE,function()
print("nextRound");
end);
end);
end
function level:moveMonster(monsterToMove)
if (monsterToMove.currentDes<=#self.route) then
monsterToMove:move(self.route[monsterToMove.currentDes]["x"],self.route[monsterToMove.currentDes]["y"]);
monsterToMove:addEventListener("monsterMoveDone",function()
monsterToMove.currentDes=monsterToMove.currentDes+1;
self:moveMonster(monsterToMove);
end);
end
end
monster.lua:
monster = Core.class(Sprite)
function monster:init(type)
local monstersList = dataSaver.load("monster");
self.instance = quickImage(monstersList[type]["image"], _W/2, _H/2,monstersList[type]["width"], monstersList[type]["height"]);
self.speed=monstersList[type]["speed"];
self.health=monstersList[type]["health"];
stage:addChild(self.instance);
---some varibles...
self.currentDes=2
end
function monster:move(desX,desY)
local time=getDistance(math.abs(self.instance:getX()-desX),math.abs(self.instance:getY()-desY))/self.speed
local mc = MovieClip.new{
{1, time, self.instance, {x = {self.instance:getX(), desX, "linear"}}},
{1, time, self.instance, {y = {self.instance:getY(), desY, "linear"}}},
}
mc:addEventListener(Event.COMPLETE,function()
self:dispatchEvent(Event.new("monsterMoveDone"))
end);
end
from the code, quickImage(); is just a little function for making image sprite
Any ideas, I thought maybe i make the memory allocating wrong.
Special Note. I run Gideros Studio under OpenSUSE 12.2 with Wine, but i don't think its a matter because all stuff go well.