Why has x become a nil value when I haven't touched it?

57 Views Asked by At

I'm learning lua using pico8 by making a platformer, but now that I have added gravity, this error:

Runtime Error line 19 tab 0
  local x1=p.x/8
Attempt to perform arithmetic on field 'x' (a nil value)

pops up when the sprite collides with an item on the map. Here is my code:

function _init()
  plr = {
    x=63,
    y=63,
    lx=63,
    ly=63,
    yv=1,
    spe=1,
    f=false
    }
  grav = 0.02
end


-- collision function --
function collision(p)

  -- point calculations
  local x1=p.x/8
  local y1=p.y/8
  local x2=(p.x+7)/8
  local y2=(p.y+7)/8
 
  -- collison checks, flag 0
  local a=fget(mget(x1, y1),0)
  local b=fget(mget(x1, y2),0)
  local c=fget(mget(x2, y1),0)
  local d=fget(mget(x2, y2),0)
 
  if a or b or c or d then
    return true
  else
    return false    
  end
 
end


-- gravity function --
function gravity(p)
  p.ly=p.y
  p.yv+=grav
 
  for i = 0, flr(p.yv) do
    if not collision(p) then
      p.y += 1
    else
      p.y = p.ly
    end
  end
end


-- move function --
function move(p)
  p.lx=flr(p.x)
  p.ly=flr(p.y)

  -- controller --
  if btn(➡️) then
    p.x+=p.spe
    p.f=true
  end
  if btn(⬅️) then
    p.x-=p.spe
    p.f=false
  end
  if btn(⬆️) then
    p.y-=p.spe
  end
    
  gravity(p)
    
  -- collision --
  if collision(p) then
    p.x=lx
    p.y=ly
  end
    
end


function _update()
  move(plr)
end


function _draw()
  cls()
  map()
  --player draw--
  spr(1,
      plr.x, plr.y, 
      1,1, plr.f)
end

What I am really confused about is why x has become a nil value when I haven't touched it in my gravity function. I have tried to do this:

if p.x == nil then
  p.x=p.lx
elseif p.y == nil then
  p.y=p.lx
end

which sort of stops the error from happening but I would like to know what the error in my code is.

1

There are 1 best solutions below

0
On

From what I can tell it is happening here:

-- collision --
  if collision(p) then
    p.x=lx
    p.y=ly
  end

as lx and ly are never set to a value in the code you have provided. Perhaps they should be a field value?