试图给玩家一个表值

时间:2017-05-14 09:18:30

标签: lua love2d

我正在用love2d编写我的第一个lua脚本,我不知道为什么我会收到错误" main.lua:4试图调用全局' Player'表值"。我的2个脚本如下: 的 - Main.lua

require("player")
function love.load()
  p = Player()
end

function love.update(dt)
  p:update(dt)
end

function love.draw()
  p:draw()
end

- Player.lua

  Player = {}
    --variables for the player (size, position, speed)

function Player:new()
  o = {
    x = 30,
    y = 30,
    w = 20,
    h = 20,
    speed = 300,
      }
  setmetatable(player, { __index = Player })
end

function Player:update(dt)
  if love.keyboard.isDown("a") then
    player.x = player.x - player.speed * dt
  end
  if love.keyboard.isDown("d") then
    player.x = player.x + player.speed * dt
    end
  if love.keyboard.isDown("w") then
    player.y = player.y + player.speed * dt
    end
  if love.keyboard.isDown("s") then
    player.y = player.y - player.speed * dt
    end
  end

function Player:draw()
  love.graphics.rectangle("fill", o.x, o.y, o.w, os.h)
end

2 个答案:

答案 0 :(得分:1)

你有一个Player表,实现了一些类。这是一张桌子,你不应该像p = Player()那样称呼它。改为调用new()方法:

function love.load()
  p = Player:new()
end

此外,new()似乎还有错误。您声明全局o变量(应该是本地的),并且您返回player而不是o,并且根本没有player。修复如下:

function Player:new()
  local player = {
    x = 30,
    y = 30,
    w = 20,
    h = 20,
    speed = 300,
      }
  return setmetatable(player, { __index = Player })
end

答案 1 :(得分:0)

尽量避免像player.lua中的播放器这样的全局变量,这就是要求麻烦

这应该有效:

main.lua

local player = require("player")

function love.load()
  p = player:new()
end

function love.update(dt)
  p:update(dt)
end

function love.draw()
  p:draw()
end

player.lua

 local Player = {}

function Player:new()
  local player = {
    x = 30,
    y = 30,
    w = 20,
    h = 20,
    speed = 300,
    }
  self.__index = self
  return setmetatable(player, self)
end

function Player:update(dt)
  if love.keyboard.isDown("a") then
    self.x = self.x - self.speed * dt
  end
  if love.keyboard.isDown("d") then
    self.x = self.x + self.speed * dt
    end
  if love.keyboard.isDown("w") then
    self.y = self.y + self.speed * dt
    end
  if love.keyboard.isDown("s") then
    self.y = self.y - self.speed * dt
    end
  end

function Player:draw()
  love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
end

return Player