Search code examples
functionluagame-enginelua-tablelove2d

Lua - limit function parameters to a certain type


I have a function called particle.new, and one of the parameters is called "colour". I need this to always be a table, but it isn't. This gives me an error because I'm using it with a function called love.graphics.setColor(), and I need to give it a table. I'm using my colour variable with it, which gives me an error because it is expecting a table and it thinks that colour isn't a table. Anyway, here's my code.

particle = {}
particle.__index = particle

function particle.new (x, y, colour, mass, drag)
  local self = setmetatable({}, particle)
  self.x, self.y, self.colour, self.mass, self.drag = x, y, colour, mass, drag
  return self
end

function particle:draw ()
  prevColor = love.graphics.getColor()
  love.graphics.setColor(self.colour)
  love.graphics.point(self.x, self.y)
  love.graphics.setColor(prevColor)
end

function particle:update ()

end

function love.load()
  gravity = -9.32
  particles = {}
  table.insert(particles, particle.new(50,50,{255, 0, 0, 255},1,0.2))
end

function love.draw()
  for i = 1, table.maxn(particles) do
    particles[i]:draw()
  end
end

By the way, I'm using the Love2D game engine.


Solution

  • Your issue is not with self.colour not being a table, it's with this line

    prevColor = love.graphics.getColor()
    

    When you do that, prevColor is only getting one of the four returned values. The solution to this is to enclose the function call in a table, so that all 4 values are kept. (Like what @EgorSkriptunoff said)

    prevColor = {love.graphics.getColor()}
    

    As for your question: Use assert and type to check the variable type

    assert(type(colour)=="table", "-Error message goes here-")
    

    Do note however, assert will throw an error which will bring up the blue love2d screen and stop your program from running.