How to fix "attempt to index a nil value"

20.9k Views Asked by At

I am having an error with my code : it keeps telling me "attempt to index a nil value (global 'sides')"

I'm trying to learn Lua through Minecraft (OpenComputers) and found myself stuck with a nil value problem. There could be things not actually from Lua (the mod itself) but the problem concerns the "pure Lua part"

component = require("component")
event = require("event")
computer = require("computer")
term = require("term")

gpu = component.gpu

redstone = component.redstone

gpu.setResolution(160,50)

while true do
    term.clear()
    term.setCursor(1,1)
    gpu.setBackground(0x5A5A5A)

    gpu.set(1,1," Allumer lampe    Eteindre lampe")
    term.setCursor(1,2)

    local _,_,x,y = event.pull("touch")

    if x >= 2 and x <= 14 and y == 1 then
        redstone.setOutput(sides.left,15)
    elseif x >= 19 and x <= 32 and y == 1 then
        redstone.setOutput(sides.left,0)
    else
        main()

    end

end

I went on the Wiki of the mod and it says that redstone.setOutput(sides.left,15) is supposed to change the actual value of the output but it also returns the OLD value of the output (and that's where I think I'm doing it wrong)

2

There are 2 best solutions below

0
On

As stated on this page, you have to call require first, like in this snippet:

local component = require("component")
local sides = require("sides")
local rs = component.redstone
rs.setOutput(sides.back, rs.getInput(sides.left))
1
On

In your code sides is not defined.

As you have this line:

redstone.setOutput(sides.left,15)

where you're trying to index sides using the indexing operator .

As sides is unknown in a nil value in this scope you cannot index it. That wouldn't make sense.

With the error message Lua complains about your attempt.

To avoid this error you must ensure that you do not index a nil value by either not indexing it or by making sure it isn't nil when you index it.

The Sides API is a module that can be loaded if needed. There is some code that creates that API within a table.

local sides = require("sides")

would execute that code and store a reference to the newly created API table in the local variable sides.

After doing so it is legitimate to index sides as sides is not nil anymore, but a table.

sides.left would refer to the value stored in the table sides for the key "left"