The following code gives me the following error:
attempt to index a nil value
-- Making grid
grid = {}
local i = 1
local ii = 1
mainx, mainy = love.graphics.getDimensions()
while(i<=mainx) do
if(i%16==0) then
while(ii<=mainy) do
if(ii%16==0) then
grid[i][ii] = nil
end
ii = ii + 1
end
end
i = i+1
end
I know lua is 1-based, but i dont really know what goes wrong here.
A fix will be gladly appericated :)
NOTE: mainx, mainy should be 800 and 600.
You forgot to assign grid[i] to {} before doing grid[i][ii] = nil. Second dereferencing [ii] fails because grid[i] == nil
I refactored your code below a little.
-- Making grid
local grid = {}
local mainx, mainy = love.graphics.getDimensions()
for i = 16,mainx,16 do -- syntax: for i = <start_value>, <max value (included)> [, <step>]
grid[i] = {};
for ii = 16,mainy,16 do
grid[i][ii] = i*ii -- some value
end
end
Related
I am trying to build a table and add to it at the end each time I get a returned value that is not already in the table. So basically what I have so far is not working at all. I'm new to LUA but not to programming in general.
local DB = {}
local DBsize = 0
function test()
local classIndex = select(3, UnitClass("player")) -- This isn't the real function, just a sample
local cifound = False
if classIndex then
if DBsize > 0 then
for y = 1, DBsize do
if DB[y] == classIndex then
cifound = True
end
end
end
if not cifound then
DBsize = DBsize + 1
DB[DBsize] = classIndex
end
end
end
Then later I'm trying to use another function to print the contents of the table:
local x = 0
print(DBsize)
for x = 1, DBsize do
print(DB[x])
end
Any help would be much appreciated
Just store a value in the table using your unique value as a key. That way you don't have to check wether a value already exists. You simply overwrite any existing keys if you have it a second time.
Simple example that stores unique values from 100 random values.
local unique_values = {}
for i = 1, 100 do
local random_value = math.random(10)
unique_values[random_value] = true
end
for k,v in pairs(unique_values) do print(k) end
I tried to fix some Garry's Mod addon and this is what happens. I tried to fix it for long time, but I'm not the best in Lua coding :/ . What is wrong with this code? I get this error:
[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
1. SetPhysicsAttacker - [C]:-1
2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80
And the code is pretty long. I have every file working fine, but this file is not working
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
if (SERVER) then
util.AddNetworkString( "gb5_net_sound_lowsh" )
end
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.GBOWNER = nil
ENT.MAX_RANGE = 0
ENT.SHOCKWAVE_INCREMENT = 0
ENT.DELAY = 0
ENT.SOUND = ""
net.Receive( "gb5_net_sound_lowsh", function( len, pl )
local sound = net.ReadString()
LocalPlayer():EmitSound(sound)
end );
function ENT:Initialize()
if (SERVER) then
self.FILTER = {}
self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
self:SetSolid( SOLID_NONE )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self.Bursts = 0
self.CURRENTRANGE = 0
self.GBOWNER = self:GetVar("GBOWNER")
self.SOUND = self:GetVar("SOUND")
end
end
function ENT:Think()
if (SERVER) then
if not self:IsValid() then return end
local pos = self:GetPos()
self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
if v:IsPlayer() then
if not (table.HasValue(self.FILTER,v)) then
net.Start("gb5_net_sound_lowsh")
net.WriteString(self.SOUND)
net.Send(v)
v:SetNWString("sound", self.SOUND)
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
if GetConVar("gb5_sound_shake"):GetInt()== 1 then
util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
end
table.insert(self.FILTER, v)
end
end
end
else
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
local ent = ents.Create("gb5_shockwave_sound_instant")
ent:SetPos( pos )
ent:Spawn()
ent:Activate()
ent:SetPhysicsAttacker(ply)
ent:SetVar("GBOWNER", self.GBOWNER)
ent:SetVar("MAX_RANGE",50000)
ent:SetVar("DELAY",0.01)
ent:SetVar("Shocktime",self.shocktime)
ent:SetVar("SOUND", self:GetVar("SOUND"))
self:Remove()
end
self.Bursts = self.Bursts + 1
if (self.CURRENTRANGE >= self.MAX_RANGE) then
self:Remove()
end
self:NextThink(CurTime() + (self.DELAY*10))
return true
end
end
function ENT:OnRemove()
if SERVER then
if self.FILTER==nil then return end
for k, v in pairs(self.FILTER) do
if not v:IsValid() then return end
v:SetNWBool("waiting", true)
end
end
end
function ENT:Draw()
return false
end
Is there a chance someone fix this for me? Or even just telling me what's wrong? I would be pleased. If needed I can send all files. Well... It's not my addon but I'm trying to fix an existing one. Someone tried to fix it too but he didn't (actually he broke it even more).
What the error means
Inside your ENT:Think() function, you are calling ent:SetPhysicsAttacker(ply)
ply is not defined anywhere inside that function, so is nil (Entity expected, got nil)
How to fix this
If no player is responsible for the damage caused by this entity, delete the line ent:SetPhysicsAttacker(ply).
Otherwise, assign an Owner to the entity at the point of creation, using SetOwner.
This would then allow you to use self:GetOwner() inside your Think hook
Example
hook.Add("PlayerSay", "SpawnEntity", function(ply, text)
if string.lower(text) == "!spawnentity" then
-- Create your entity
local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
myEntity:SetPos(ply:GetPos())
myEntity:SetAngles(ply:GetAngles())
myEntity:Spawn()
-- Sets the owner to the player that typed the command
myEntity:SetOwner(ply)
return ""
end
end)
-- Inside your entity code
function ENT:Think()
print("My owner is: " .. tostring(self:GetOwner()))
-- ...
ent:SetPhysicsAttacker(self:GetOwner())
end
I have decompiled a few lua codes, was able to understand most of them.
But there are these UPVALUE0, UPVALUE1, etc... keywords I see in the code that are not defined anywhere as far as I've looked.
Here's an example:
local L0_0
L0_0 = module
L0_0((...), package.seeall)
function L0_0(A0_1)
if A0_1 - math.floor(A0_1) > 0 then
error("trying to use bitwise operation on non-integer!")
end
end
bit = {
bxor = function(A0_17, A1_18)
local L2_19, L3_20, L4_21, L5_22
L2_19 = _UPVALUE0_
L3_20 = A0_17
L2_19 = L2_19(L3_20)
L3_20 = _UPVALUE0_
L4_21 = A1_18
L3_20 = L3_20(L4_21)
L4_21 = _UPVALUE1_
L5_22 = L2_19
L4_21(L5_22, L3_20)
L4_21 = {}
L5_22 = math
L5_22 = L5_22.max
L5_22 = L5_22(table.getn(L2_19), table.getn(L3_20))
for _FORV_9_ = 1, L5_22 do
if L2_19[_FORV_9_] ~= L3_20[_FORV_9_] then
L4_21[_FORV_9_] = 1
else
L4_21[_FORV_9_] = 0
end
end
return _UPVALUE2_(L4_21)
end
}
What do they mean?
From https://www.lua.org/pil/6.1.html:
.. is neither a global variable nor a local variable. We call it an
external local variable, or an upvalue. (The term "upvalue" is a
little misleading, because it is a variable, not a value. However,
this term has historical roots in Lua and it is shorter than "external
local variable".)
local i = 0
function inc()
i = i + 1
return i
end
Variable i in function inc is upvalue, as it is not local variable in this function and not global variable.
I'm trying to shuffle a table's contents randomly. It works fine, except sometimes it doesn't return all the contents of the table. I printed out some of the keys of the table before shuffling, and they returned nil, but I'm not sure how to fix that. Here's the Lua:
local tab = {1,2,3,4,5,6,7,8,9,10}
function ReturnRandomTable(t)
local newt = {}
local i = 1
repeat
local rand = math.random(1,#t)
newt[i] = t[rand]
print(t[rand]) --sometimes prints nil
t[rand] = nil
i = i + 1
until #t == 0
return newt
end
table.shuffle = function(t)
local newt = ReturnRandomTable(t)
for i = #t,1,-1 do
t[i] = nil
end
return newt
end
local randt = table.shuffle(tab)
for _,v in pairs(randt) do
print(v)
end
Any help would be appreciated!
Solved by changing t[rand] = nil to table.remove(t,rand).
I'm trouble to understand self and local value.
Here is my asteroid.lua. I created local asteroid inside :create and was trying to use it other function but it is not working correctly.
-- Class Declaration
Asteroid = {}
Asteroid.__index = Asteroid
function Asteroid:create()
local asteroid = {}
setmetatable(asteroid, Asteroid)
-- Animation Data
asteroid.frames = {}
asteroid.currentFrame = 1
asteroid.frameDuration = 0.04 -- 0.016
asteroid.frameTimeRemaining = asteroid.frameDuration
asteroid.x = 0
asteroid.y = 0
return asteroid
end
function Asteroid:init()
-- Use a loop to load a bunch of files!
for index= 0, 15 do
-- Use logic to build the filename...
file = 'art/large/a100'
-- Take into account the extra 0
if index < 10 then
file = file .. '0'
end
-- Add the file number and then .png
file = file .. tostring(index) .. '.png'
-- Load the file... (we'll use lua's 1 index to be kind)
self.frames[index + 1] = love.graphics.newImage(file)
if self.frames[index + 1] ~= nil then
print('Loaded frame ' .. tostring(index + 1))
end
end
-- Set the velocity randomly!
self.velocity = {}
self.velocity.x = math.random(-76.0, 76.0)
self.velocity.y = math.random(-76.0, 76.0)
end
Asteroid.updateAnimation = function(deltaTime)
-- Catch variable into 'easy-to-type' one
local ftr = Asteroid.frameTimeRemaining
THIS PART(local ftr) IS MY PROBLEM: ATTEMPT TO INDEX A NIL VALUE.
I tried different ways like self.frameTimeRemaing but I couldn't figure out.
Is anyone know how I can fix this local?
-- Subtract time
ftr = ftr - deltaTime
-- If the frame is over...
if ftr < 0 then
Asteroid.nextFrame()
Asteroid.frameTimeRemaining = Asteroid.frameDuration
else
Asteroid.frameTimeRemaining = ftr
end
end
Without seeing the rest of the code, I can only guess. Try this:
function Asteroid:updateAnimation(deltaTime)
-- use self instead of Asteroid in this function
end