attempt to index global ' self ' (a nil value) - lua

I ran this code and it gave me an error attempt to index global 'self' (a nil value)
hook.Add( "PostDrawOpaqueRenderables","2d3d", function( )
cam.Start3D2D( Vector( self.Entity:GetPos() ), Angle(0, -90, 90), 1 )
surface.SetDrawColor( 255, 0, 255 )
surface.DrawTexturedRect( 0, 0, 500, 500 )
cam.End3D2D()
end)

You can use hook.Entity:GetPos() fix this error.
self is a lua keyword, that appears in the method definition of a table.

Related

lua/pivohelperv2.lua:127: unexpected symbol near ')'

Pls can u help me, thats not all of the code but in this piece problem. Thats Glua and i hope u help me!!!
local dPanelButton1 = vgui.Create( 'DButton', dPanelDa) --Кнопка для лотки
dPanelButton1:SetSize( 250, 50 )
dPanelButton1:SetPos( 625, 370 )
dPanelButton1:SetText( '' )
dPanelButton1.Paint = function( self, w, h )
draw.RoundedBox( 30, 0, 0, w, h, Color( 90, 90, 90, 200 ) )
draw.SimpleText( "Админский ПивоХелп", "help", w / 2, h / 2.0, Color( 224, 184, 128 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
end
dPanelButton1.DoClick = function()
local dPanelDa = vgui.Create( 'DFrame')
dPanelDa:SetSize( 500, 300 )
dPanelDa:SetPos( ScrW() / 2 - 450, ScrH() / 2 - 250)
dPanelDa:SetTitle( ' Админский ПивоХелп ' )
dPanelDa:ShowCloseButton( true )
dPanelDa:MakePopup()
dPanelDa.Paint = function( self, w, h )
draw.RoundedBox( 5, 0, 0, w, h, Color(90, 90, 90, 200) )
draw.RoundedBox( 5, 2, 2, w, 25, Color(224, 184, 128) )
end
end
timer.Simple( 1, function() PivoDerma() end ) -- потнич
end)
add some more details!add some more details!add some more detailsadd some more detailsadd some more detailsadd some more detailsadd some more detailsadd some more detailsadd some more detailsadd some more detailsadd some more details
You have an extra end) at the end of the code block. I assume that's line 127, right? That is, unless this code is inside a block that starts somewhere we can't see in your except.
Be sure to be careful with identation when writing function blocks! It helps to make sure your function() blocks are properly closed with a corresponding end.
One extra thing. This:
dPanelButton1.Paint = function( self, w, h )
...
end
Can instead be written as:
function dPanelButton1:Paint( w, h )
-- the 'self' arg can be omitted by using colons ":" instead of dot "." during declaration and calls.
-- this is the most common way of passing the table the function is stored in as the first argument, implicitly named `self`.
-- In other words, calling `dPanelButton1:Paint(1, 2)` is the same as calling `dPanelButton1.Paint(dPanelButton1, 1, 2)`
...
end
And this:
dPanelButton1.DoClick = function()
...
end
Could be written as:
function dPanelButton1.DoClick()
-- Writing `function foo(arg)` is the same as writing `foo = function(arg)`.
...
end
This makes the function blocks clearer in the code and is easier for others to read. Clean readable code is how you prevent syntax errors (well, that and an IDE).

GLua - part of the string library

I have gui wherein I need show information from table
When I open gui, I have this error:
"attempt to index a string value with bad key ('Index' is not part of the string library)"
SH file. In this file I put table information
MyList = {}
MyList = {
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
CL file. This file contains the part of the code where the error occurs. The error occurs on the first line
for k, v in SortedPairsByMemberValue( MyList, "Index" ) do
if v.Class == "exampleclass" then
local mainbuttons = vgui.Create( "DCollapsibleCategory", category )
mainbuttons:Dock(TOP)
mainbuttons:DockMargin(0, 6, 0, 2)
mainbuttons.Header:SetTall(24)
mainbuttons:SetExpanded(0)
mainbuttons:SetLabel("")
mainbuttons.Text = v.Name
function mainbuttons:Paint(w, h)
local h = 24
surface.SetDrawColor(v.Color)
surface.DrawRect(0, 0, w, h)
surface.SetFont("NovuxFont.ArialLight.16")
local textw, texth = surface.GetTextSize(self.Text)
surface.SetTextColor(Color(255, 255, 255))
surface.SetTextPos(16, h / 2 - texth / 2)
surface.DrawText(self.Text)
end
local craftpanel = vgui.Create( "DPanel", mainbuttons )
craftpanel:SetPos( 0, 25 )
craftpanel:SetSize( mainframescroll:GetWide(), 250 )
craftpanel.Paint = function() -- Paint function
surface.SetDrawColor( 65, 65, 65, 0 )
surface.DrawRect( 0, 0, craftpanel:GetWide(), craftpanel:GetTall() )
end
local spoilertext = vgui.Create( "DLabel", mainbuttons )
spoilertext:SetText( v.Description )
spoilertext:SetTextColor( Color( 255, 255, 255 ) )
spoilertext:SetFont( "NovuxFont.ArialLight.16" )
spoilertext:SetPos( 108, 32 )
spoilertext:SetSize( mainframescroll:GetWide(), 25 )
spoilertext.Paint = function( self, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 102, 102, 102, 0 ))
end
local modelframe = vgui.Create( "DModelPanel", mainbuttons )
modelframe:SetPos( 0, 65 )
modelframe:SetSize( 300, 200 )
modelframe:SetModel( v.Model )
modelframe:GetEntity():SetAngles( Angle( -10, 0, 15 ) )
local mn, mx = modelframe.Entity:GetRenderBounds()
local size = 0
size = math.max( size, math.abs( mn.x ) + math.abs( mx.x ) )
size = math.max( size, math.abs( mn.y ) + math.abs( mx.y ) )
size = math.max( size, math.abs( mn.z ) + math.abs( mx.z ) )
modelframe:SetFOV( 45 )
modelframe:SetCamPos( Vector( size, size, size ) )
modelframe:SetLookAt( (mn + mx) * 0.5 )
function modelframe:LayoutEntity( Entity )
return
end
end
end
The problem is that you put the whole item in MyList where by logic of SortedPairsByMemberValue you supposed to put new table inside MyList.
This fixes the problem:
MyList = {
{
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
}
Notice that now this is a nested table.

attempt to call global 'addButtons' (a nil value)

I need help with a really annoying error I've been getting with my GMOD gamemode. I am trying to make a custom menu, but I get this error:
[ERROR] gamemodes/tdm/gamemode/custom_menu.lua:20: attempt to call global 'addButtons' (a nil value)
1. gameMenu - gamemodes/tdm/gamemode/custom_menu.lua:20
2. unknown - gamemodes/tdm/gamemode/custom_menu.lua:32
3. include - [C]:-1
4. unknown - gamemodes/tdm/gamemode/cl_init.lua:3
Here is my code:
custom_menu.lua
local Menu
function gameMenu()
if(Menu == nil) then
Menu = vgui.Create("DFrame")
Menu:SetSize(750, 500)
Menu:SetPos(ScrW() / 2 - 325, ScrH() / 2 - 250)
Menu:SetTitle("Gamemode Menu")
Menu:SetDraggable(true)
Menu:ShowCloseButton(false)
Menu:SetDeleteOnClose(false)
Menu.Paint = function()
surface.SetDrawColor(60, 60, 60, 255)
surface.DrawRect(0, 0, Menu:GetWide(), Menu:GetTall())
surface.SetDrawColor(40, 40, 40, 255)
surface.DrawRect(0, 24, Menu:GetWide(), 1)
end
addButtons(Menu)
gui.EnableScreenClicker(true)
else
if(Menu:IsVisible()) then
Menu:SetVisible(false)
gui.EnableScreenClicker(false)
else
Menu:SetVisible(true)
gui.EnableScreenClicker(true)
end
end
end
concommand.Add("open_game_menu", gameMenu())
function addButtons(Menu)
local playerButton = vgui.Create("DButton")
playerButton:SetParent(Menu)
playerButton:SetText("")
playerButton:SetSize(100, 50)
playerButton:SetPos(0, 25)
playerButton.Paint = function()
--Color of entire button
surface.SetDrawColor(50, 50, 50, 255)
surface.DrawRect(0, 0, playerButton:GetWide(), playerButton:GetTall())
--Draw Bottom and Right borders
surface.SetDrawColor(40, 40, 40, 255)
surface.DrawRect(0, 49, playerButton:GetWide(), 1)
surface.DrawRect(99, 0, 1, playerButton:GetTall())
--Draw Text
draw.DrawText("Player", "DermaDefaultBold", playerButton:GetWide() / 2, 17, Color(255, 255, 255, 255), 1)
end
playerButton.DoClick = function(playerButton)
local playerPanel = Menu:Add("PlayerPanel")
end
local shopButton = vgui.Create("DButton")
shopButton:SetParent(Menu)
shopButton:SetText("")
shopButton:SetSize(100, 50)
shopButton:SetPos(0, 75)
shopButton.Paint = function()
--Color of entire button
surface.SetDrawColor(50, 50, 50, 255)
surface.DrawRect(0, 0, shopButton:GetWide(), shopButton:GetTall())
--Draw Bottom and Right borders
surface.SetDrawColor(40, 40, 40, 255)
surface.DrawRect(0, 49, shopButton:GetWide(), 1)
surface.DrawRect(99, 0, 1, shopButton:GetTall())
--Draw Text
draw.DrawText("Shop", "DermaDefaultBold", shopButton:GetWide() / 2, 17, Color(255, 255, 255, 255), 1)
end
shopButton.DoClick = function(shopButton)
local shopPanel = Menu:Add("ShopPanel")
end
end
--Player Panel
PANEL = {} -- Create an empty panel
function PANEL:Init() --Initialize the panel
self:SetSize(650, 475)
self:SetPos(100, 25)
end
function PANEL:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 255))
end
vgui.Register("PlayerPanel", PANEL, "Panel")
--End Player Panel
--Shop Panel
PANEL = {} -- Create an empty panel
function PANEL:Init() --Initialize the panel
self:SetSize(650, 475)
self:SetPos(100, 25)
end
function PANEL:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(255, 255, 255, 255))
end
vgui.Register("ShopPanel", PANEL, "Panel")
--End Shop Panel
init.lua:
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "testhud.lua" )
local open = false
include ( 'shared.lua' )
local open = false
function GM:PlayerInitialSpawn(ply)
if(ply:GetPData("playerLvl") == nil) then
ply:SetNWInt("playerLvl", 1)
else
ply:SetNWInt("playerLvl", ply:GetPData("playerLvl"))
end
if(ply:GetPData("playerExp") == nil) then
ply:SetNWInt("playerExp", 0)
else
ply:SetNWInt("playerExp", ply:GetPData("playerExp"))
end
if(ply:GetPData("playerMoney") == nil) then
ply:SetNWInt("playerMoney", 0)
else
ply:SetNWInt("playerMoney", ply:GetPData("playerMoney"))
end
end
function GM:OnNPCKilled(npc, attacker, inflictor)
attacker:SetNWInt("playerMoney", attacker:GetNWInt("playerMoney") + 100)
attacker:SetNWInt("playerExp", attacker:GetNWInt("playerExp") + 100)
checkForLevel(attacker)
end
function GM:PlayerDeath(victim, inflictor, attacker)
attacker:SetNWInt("playerMoney", attacker:GetNWInt("playerMoney") + 100)
attacker:SetNWInt("playerExp", attacker:GetNWInt("playerExp") + 100)
checkForLevel(attacker)
end
function GM:PlayerLoadout(ply)
ply:Give("m9k_l85")
ply:Give("m9k_colt1911")
ply:Give("m9k_knife")
ply:Give("m9k_m61_frag")
ply:GiveAmmo(500, "ar2", true)
ply:GiveAmmo(100, "pistol", true)
return true
end
function checkForLevel(ply)
local expToLevel = (ply:GetNWInt("playerLvl") * 100) * 2
local curExp = ply:GetNWInt("playerExp")
local curLvl = ply:GetNWInt("playerLvl")
if(curExp >= expToLevel) then
curExp = curExp - expToLevel
ply:SetNWInt("playerExp", curExp)
ply:SetNWInt("playerLvl", curLvl + 1)
end
end
function GM:PlayerDisconnected(ply)
ply:SetPData("playerExp", ply:GetNWInt("playerExp"))
ply:SetPData("playerLvl", ply:GetNWInt("playerLvl"))
ply:SetPData("playerMoney", ply:GetNWInt("playerMoney"))
end
function GM:ShutDown()
for k, v in pairs(player.GetAll()) do
v:SetPData("playerExp", v:GetNWInt("playerExp"))
v:SetPData("playerLvl", v:GetNWInt("playerLvl"))
v:SetPData("playerMoney", v:GetNWInt("playerMoney"))
end
end
function GM:ShowSpare2(ply)
ply:ConCommand("open_game_menu")
end
Thanks!
-Graham
You call
concommand.Add("open_game_menu", gameMenu())
which calls addButtons(Menu) which is nil at this point as the function definition follows after concommand.Add("open_game_menu", gameMenu()).
It's all there. You just have to read the error message.
Change the order in your script to fix the error.

Garry's mod menu script (lua)

function Team_Swap()
local Backg = vgui.Create( "DFrame" )
Backg:SetSize( ScrW() / 2, ScrH() / 2 )
Backg:SetPos ( ScrW() / 2, ScrH() / 2 )
Backg:SetTitle( "Swap Teams" )
Backg:SetVisible ( true )
Backg:SetDraggable ( true )
Backg:ShowCloseButton ( true )
Backg:MakePopup()
local DColorButton = vgui.Create ( "DColorButton", Backg )
DColorButton:SetPos( 40, 40 )
DColorButton:Paint( 100, 40 )
DColorButton:SetSize( 100, 40 )
DColorButton:SetText( "Join Red Team", Color( 221,78,76 ) )
DColorButton:SetColor( Color( 221,78,76 )
function DColorButton:DoClick(player)
player:Kill()
player:SetTeam(1)
player:Spawn()
end
end
concommand.Add( "set_team", Team_Swap )
This code runs fine... until you do its only purpose CLICK THE BUTTON
the button when clicked returns the following text in console
newrecycle]set_team
[ERROR] gamemodes/capturetheflag/gamemode/cl_init.lua:32: attempt to index local 'player' (a nil value)
1. DoClick - gamemodes/capturetheflag/gamemode/cl_init.lua:32
2. unknown - lua/vgui/dlabel.lua:218
[n3wr3cycl3|20|STEAM_0:1:59994487] Lua Error:
[ERROR] gamemodes/capturetheflag/gamemode/cl_init.lua:32: attempt to index local 'player' (a nil value)
1. DoClick - gamemodes/capturetheflag/gamemode/cl_init.lua:32
2. unknown - lua/vgui/dlabel.lua:218
please help!
First of all: You are mixing Clientside (vgui) and Serverside (Player:SetTeam()) Stuff.
(Explanation why you are running in this Error is in the Clientside Script)
My suggestion:
Clientside Script:
function Team_Select()
local Backg = vgui.Create( "DFrame" )
Backg:SetSize( ScrW() / 2, ScrH() / 2 )
Backg:SetPos ( ScrW() / 2, ScrH() / 2 )
Backg:SetTitle( "Swap Teams" )
Backg:SetVisible ( true )
Backg:SetDraggable ( true )
Backg:ShowCloseButton ( true )
Backg:MakePopup()
local TeamRedButton = vgui.Create ( "DColorButton", Backg )
TeamRedButton:SetPos( 40, 40 )
TeamRedButton:Paint( 100, 40 )
TeamRedButton:SetSize( 100, 40 )
TeamRedButton:SetText( "Join Red Team", Color( 221,78,76 ) )
TeamRedButton:SetColor( Color( 221,78,76 )
function TeamRedButton:DoClick() -- DoClick has 0 Params
RunConsoleCommand("switchteam", "red")
end
end
concommand.Add( "chooseteam", Team_Select )
And Serverside Script:
function Team_Switch( --[[ Player ]] player, --[[ String ]] cmd, --[[ Table ]] args)
-- Get the Parameter out of the Table (in my example "red" for the red team)
-- and move the player to the choosen Team
end
concommand.Add("switchteam", Team_Switch)
The Clientside Script is just the GUI for the user. The actual Teamswitch is handled by the server and can be initialized from the Client console as well.
The user is able to execute switchteam red directly
Source: My Experience and the GMod Wiki

Group Display Objects vs. Tables in Corona Lua

First time post and I sincerely apologize if this has been answered in any other post but I have not been able to find a resolution for the problem I'm facing on this or any other site. I'm a new programmer self-teaching with web tutorials and any other resource I have found. I am trying to create code which will spawn characters and allow you to call them. I've had trouble assigning an index value to the individual instances I have created with a for function. I have tried to establish the instance as both a table and a group display object. If anyone is able to point me in the direction of any resources to get a more indepth understanding of tables and group display objects for the Corona SDK implementation of Lua I'm sure that my problem is that I don't have a thorough enough understanding of these particular functionalities and how they work. Here is the code I've written so far.
-- Character Game
require "sprite"
require "ui"
local background = display.newImage("Background Placeholder.png")
halfW = display.viewableContentWidth / 2
halfH = display.viewableContentHeight / 2
local numCharacters = 20
local roundedRect = display.newRoundedRect( 365, 20, 110, 40, 8 )
roundedRect:setFillColor( 0, 255, 0, 80 )
score = 0
t = ui.newLabel{ bounds = { 370, 30, 100, 40 },
text = "Score " .. score,
textColor = { 255, 0, 20, 255 },
size = 18,
align = "center"
}
local scoreboard = function ( event )
t:setText( "Score " .. score )
end
Runtime:addEventListener( "enterFrame", scoreboard )
local group = display.newGroup()
local character = sprite.newSpriteSheetFromData( "Character Placeholder.png", require("Character Placeholder").getSpriteSheetData() )
local characterSet1 = sprite.newSpriteSet(character,1,8)
sprite.add(characterSet1,"character",1,8,1500,0)
local characterplay = function( event )
score = score + group.points
group[i]:removeSelf()
end
do
for i=1, numCharacters do
group:insert(sprite.newSprite(characterSet1))
group[i].xScale = .2
group[i].yScale = .2
group.points = 50
group[i]:setReferencePoint ( display.BottomCenterReferencePoint )
group[i]:translate( halfW + math.random( -100, 100 ), halfH + math.random( -130, -110 ) )
end
timer.performWithDelay( 500, charactermovie )
for i=1, 21 do
timer.performWithDelay( math.random( 500, 5000 ) , charactermove )
charactermove = function(event )
transition.to( group[i], { time=10000, y = 580 } )
transition.to( group[i], { time=8000, x = math.random( 0, 480 ) } )
transition.to( group[i], { time=7000, xScale = 1.5} )
transition.to( group[i], { time=7000, yScale = 1.5} )
group[i]:prepare("character")
group[i]:play()
end
group[i]:addEventListener( "tap", characterplay )
end
end
charactermovie = function( event )
group[i]:prepare("character")
group[i]:play()
end
local function spriteListener( event )
print( "Sprite event: ", event.sprite, event.sprite.sequence, event.phase )
end
for i, group in pairs(group) do print (group, i, v) end
I'm currently getting an "attempt to index field '?' at the line containing this code "group[i]:addEventListener( "tap", zombieplay )" upon launch and a "nil key supplied for property lookup" error at the "group[i]:removeSelf()" line of the "zombieplay" function. I've tried moving the offending code to a variety of locations to see if this is a scoping issue but I largely run into the same error and believe I may not properly understand indexes and keys... I've found that the app functions as intended but I have to call index keys 1 through 21 to get them all to move even though I am only calling for 20 characters and the removeSelf line throwing errors is not removing the individual characters. I'm going to try writing a module for the characters and see if that helps clear any of this up. I will post my results shortly.
Your characterplay and charactermovie functions are trying to use the variable i, this is outside the functions scope.
There is a property of event called target, which is used to get the event callee. You want to do something like this:
local characterplay = function( event )
score = score + group.points
event.target:removeSelf()
end

Resources