Search code examples
lualove2d

A table element becomes nil, after it is set to an integer


I am trying to make a Basic Entity Component System and I’ve got this error on my lua scripts (working with Love2D). I don´t know where the problem is:

Error: systems.lua:11: bad argument #2 to 'rectangle' (number expected, got nil)

main.lua

local system = require "systems"

function love.load()
    system.newPlayer()
end

function love.draw()
    system.drawPlayer()
end

systems.lua

local S = {}

local entities = require "entities"
local components = require "components"

function S.newPlayer()
    entities.player()
end

function S.drawPlayer()
    love.graphics.rectangle("fill",components.getX(1),components.getY(1), 10, 10)
end

return S

entities.lua

local components = require "components"

local E = {}

function E.player()
    components.setX(1,20)
    components.setY(1,20)
end

return E

components.lua

local C = {}

local x = {}
function C.setX(key, value)
    x.key = value
end
function C.getX(index)
    return x.index
end

local y = {}
function C.setY(key, value)
    y.key = value
end
function C.getY(index)
    return y.index
end

return C

I trace the error to entities.lua when calling components.setX(1,20), because after that, printing the key´s value is nil, eventhough the function set it to 20.


Solution

  • In

    x.key = value
    

    the key is the string value "key".

    If you want the key to be the value of the variable key, do

    x[key] = value