Gmod 13 Lua Error - lua

I am trying to learn Lua and I decided that for my first project I would try to fix a broken script. I have fixed a few of the bugs but I'm stuck now. Can you help me?
function SWEP:PrimaryAttack()
if( CurTime() < self.NextStrike ) then return; end
self.Weapon:EmitSound("player/skick/sparta.mp3")
self.NextStrike = ( CurTime() + 3.5 );
timer.Simple( 1.80, function() self:AttackAnim() end)
-Next line broken-
timer.Simple( 2.40, function() self.Weapon:SendWeaponAnim( ACT_VM_IDLE ) end);
timer.Simple( 2.00, function() self.ShootBullets( self ) end)
self.Owner:SetAnimation( PLAYER_ATTACK1 );
end
function SWEP:ShootBullets()
-Next line Broken-
local trace =Owner:GetEyeTrace();
if trace.HitPos:Distance(self.Owner:GetShootPos()) <= 130 then
if( trace.Entity:IsPlayer() or trace.Entity:IsNPC() or trace.Entity:GetClass()=="prop_ragdoll" ) then
timer.Simple(0, game.ConsoleCommand, "host_timescale 0.1\n")
timer.Simple(0.5, game.ConsoleCommand, "host_timescale 1\n")
self.Owner:EmitSound( self.FleshHit[math.random(1,#self.FleshHit)] );
else
self.Owner:EmitSound( self.Hit[math.random(1,#self.Hit)] );
end
bullet = {}
bullet.Num = 5
bullet.Src = self.Owner:GetShootPos()
bullet.Dir = self.Owner:GetAimVector()
bullet.Spread = Vector(0.04, 0.04, 0.04)
bullet.Tracer = 0
bullet.Force = 250
bullet.Damage = 1000000
self.Owner:FireBullets(bullet)
end
I'm getting an error saying Attempting to index field 'Weapon' (a nil value).
Can anyone explain how to fix this?
Im not allowed to post imagesthis is what im getting Error image

The reason you're getting that error is that "Weapon" (specifically self.Weapon) was not initialized. self.Weapon points to nothing, so you can't call any functions on it.
Can you show us the lines that the error messages reference? It looks like the file is shared.lua, lines 84, 85 and 90. The surrounding code would be helpful, too. I'm guessing that you posted it as part of your original question, but it's not helpful without any line numbers!

Related

I have a gLua error: bad argument #1 to 'lower' (string expected, got nil)

I want to create a command that would change your model when typing "!swap" and make it so it would return to your previous model when you type it again and repeat.
I have tried ending the function and continuing on but that hasn't worked. I need someone to explain the error as I have never seen it before and google/gmod wiki doesn't show it either.
hook.Add( 'PlayerSay', 'PlayerSayExample', function (ply, text, team)
end )
if ( string.sub( string.lower( text ), 1, 5 ) == "!swap" ) then
local model = ply:GetModel()
function GM:PlayerSetModel( ply ) end
else
end
if model == ("models/Kleiner.mdl") then
ply:SetModel("models/Eli.mdl")
else
ply:SetModel("models/Kleiner.mdl")
end
===================================
[ERROR] lua/swap2.lua:3: bad argument #1 to 'lower' (string expected, got nil)
1. lower - [C]:-1
2. unknown - lua/swap2.lua:3
===================================
above (between the breaks) is the error I am getting. It occurs on the "string.lower" bit on line 3 but I don't know what is actually wrong with the code, as I haven't seen the error before.
hook.Add( 'PlayerSay', 'PlayerSayExample', function (ply, text, team)
end )
Means that your hook is empty.
If you do not define text before or after the hook, text is nil and will always throw this error. Here is your fix:
hook.Add( 'PlayerSay', 'PlayerSayExample', function (ply, text, team)
if ( string.sub( string.lower( text ), 1, 5 ) == "!swap" ) then
local model = ply:GetModel()
function GM:PlayerSetModel( ply ) end
else
end
if model == ("models/Kleiner.mdl") then
ply:SetModel("models/Eli.mdl")
else
ply:SetModel("models/Kleiner.mdl")
end
end )

GMod | Want to make a simple command that prints a colored message in the senders chatbox

I just want to make a simple script that prints a colored text in the chat of the sender after executing a specific command.
First the console gave me an error [attempt to index global 'chat' (a nil value)]. After reloading the Singleplayer and opening the script it didn't do anything.
Current Code:
local ply = LocalPlayer()
local function Test( ply, text, team )
if string.sub( text, 1, 8 ) == "!command" then
chat.AddText( Color( 100, 100, 255 ), "Test" )
end
end
hook.Add( "PlayerSay", "Test", Test )
I hope that someone could help me.
You're using LocalPlayer() (which is only called client-side) as well as chat.AddText() (again, only called client-side) inside of a "PlayerSay" hook (which is a server-side hook). You'd need something else, like ChatPrint()
EDIT: Just realized ChatPrint() doesn't accept Color() arguments in it... you could always try sending a net message:
if SERVER then
util.AddNetworkString( "SendColouredChat" )
function SendColouredChat( ply, text )
if string.sub( text, 1, 8 ) == "!command" then
net.Start( "SendColouredChat" )
net.WriteTable( Color( 255, 0, 0, 255 ) )
net.WriteString( "Test" )
net.Send( ply )
end
end
hook.Add( "PlayerSay", "SendColouredChat", SendColouredChat )
end
if CLIENT then
function ReceiveColouredChat()
local color = net.ReadTable()
local str = net.ReadString()
chat.AddText( color, str )
end
net.Receive( "SendColouredChat", ReceiveColouredChat )
end
EDIT: Returned to this question after a few years. For anyone else who may run into this later on, it's much simpler to just use the GM:OnPlayerChat hook.
local function Command(ply, text, teamOnly, dead)
if text:sub(1, 8) == "!command" then
chat.AddText(Color(100, 100, 255), "Test")
end
end
hook.Add("OnPlayerChat", "TestCommand", Command)

Coronasdk Issue with addeventListeners

recently I was coding a new game when I ran across a problem of which I cannot seem to be able to fix.
This is the code :
function newPower()
rand = math.random( 100 )
if (rand < 80) then
powerup = display.newImage("power.png");
powerup.class = "powerup"
powerup.x = 60 + math.random( 160 )
powerup.y = -100
physics.addBody( powerup, { density=0.9, friction=0.3, bounce=0.3} )
powerup:addEventListener( "touch", handlePowerTouch )
end
end
local function handlePowerTouch( event )
if event.phase == "began" then
currentScore = currentScore * 2
currentScoreDisplay.text = string.format( "%06d", currentScore )
event.target:removeSelf()
return true
end
end
local function spawnpowers()
-- Spawn a new powerup every second until canceled.
spawnPower = timer.performWithDelay( 1000, newPower, -1 )
end
Any help fixing this issue would be greatly appreciated!
The issue I'm having is when I click "run" or "play" the game starts working then crashes and displays this message:
addEventListener: listener cannot be nil: nil stack traceback:
?: in function 'addeventListener'
game.lua63: in function'_listener' <-- i have given you game.lua:63 above.
Thanks
powerup:addEventListener( "touch", handlePowerTouch )
Here handlePowerTouch is nil as the function definition follows after this line.
Move your function definition in front of that line, then it should work.
Btw, is there any reason why you have so many global variables? You should use local variables wherever possible.

corona sdk error on line creation

I do not understand why I get the following error:
Line: 107
Bad argument #1 to 'newLine' (number expected, got nil)
I am trying to create a line between two touched objects.
Here is my code:
function createstar()
ie = ie - 300
astar = display.newImage('ls.png', math.random( 1, 10) * 33, ie)
astar:addEventListener( "touch", star)
physics.addBody(astar)
stars:insert(astar)
sceneGroup:insert(stars)
end
function update(e)
if(stars ~= nil)then
for i = 1, stars.numChildren do
stars[i].y = stars[i].y + 3
end
end
end
function star:touch( event )
if event.phase == "began" then
-- Insert touched star into array
table.insert(touchedStarArray, self)
-- Check if array holds 2 stars yet
if table.getn(touchedStarArray) >= 2 then
-- if it does then draw a line between the 2 stars
line = display.newLine( touchedStarArray[1].x, touchedStarArray[1].y, touchedStarArray[2].x, touchedStarArray[1].y)
-- and empty array
touchedStarArray = {}
end
end
end
Thanks in advance, all help is greatly appreciated!
I assume from code you pasted that you have one table listener and it's not the same object as each star created.
The problem is in this line
table.insert(touchedStarArray, self)
There are to ways to solve it.
One, very simple would be to put into touchedStarArray event.target not self (self is table star, not star's objects you are createing in createstar function.
table.insert(touchedStarArray, event.target)
Other solution would be to put listener into star creation function
function createstar()
ie = ie - 300
astar = display.newImage('ls.png', math.random( 1, 10) * 33, ie)
astar:addEventListener( "touch", astar)
function astar:touch( event )
if event.phase == "began" then
-- Insert touched star into array
table.insert(touchedStarArray, self)
-- Check if array holds 2 stars yet
if table.getn(touchedStarArray) >= 2 then
-- if it does then draw a line between the 2 stars
line = display.newLine( touchedStarArray[1].x, touchedStarArray[1].y, touchedStarArray[2].x, touchedStarArray[1].y)
-- and empty array
touchedStarArray = {}
end
end
end
physics.addBody(astar)
stars:insert(astar)
sceneGroup:insert(stars)
end
I would put in some print statements and make sure that touchedStarArray[1] really has a .x attribute.
\

Lua stack overflow in recursive function in corona sdk

For some reason the code below throws a stack overflow error if the else statement gets executed too many times. I am trying to have the scene.targeting function select a target from the objTable passed in the params, but only targets with a .tgtFlag == false are valid selections. If the function selects a target that has a .tgtFlag == true, it recalls the scene.targeting function passing in the same set of params.
The line that breaks is local theTarget = params.objTable[math.random( 1, #params.objTable )] but only after else scene.targeting(params) end is called several times.
Any help would be greatly appreciated.
function scene.targeting( params ) -- Targeting functions
function animateTarget( target )
if target.savedFlag == false then
transition.to( target, {time = 100, y = target.y - 15} )
transition.to( target, {time = 100, delay = 150, y = target.y, onComplete = animateTarget} )
end
end
local theTarget = params.objTable[math.random( 1, #params.objTable )]
if theTarget.tgtFlag == false then
theTarget.tgtFlag = true
animateTarget(theTarget)
else
scene.targeting(params)
end
end
Referring to Programming in Lua:
A tail call is a kind of goto dressed as a call. A tail call happens when a function calls another as its last action, so it has nothing else to do.
In your example, animateTarget obviously isn't called in such a way, and can and will suffer from stack overflows. Either rewrite it to make use of TCO or change it to non-recursive version.

Resources