This code is a function in an api called "marik" that I created with my own functions. I called the function with marik.pLoad() in the main program. The code works if used in the main program, so the code itself isn't an issue. Once I moved it to the API (which is loaded with lots of other functions that I use) then called the function, the main program doesn't know about machines{}. It's not local, so I don't know why it isn't visible.
API code:
function pLoad()
machines = peripheral.getNames() -- load a list of peripherals into a table
table.sort(machines) -- so it displays in non-random manner
end
Main program code:
marik.pLoad()
for i=1, #machines do
-- the rest is omitted
Error: attempt to get length of nil from this line:
for i=1, #machines do
I think I understand what's going on now. I assume you have two files, something like this.
module(..., package.seeall)
function pLoad()
machines = peripheral.getNames() -- load a list of peripherals into a table
table.sort(machines) -- so it displays in non-random manner
end
require'marik'
marik.pLoad()
for i=1, #machines do -- error here
So the problem is that because marik is in a module, it won't be accessing your main globals table. Instead, it will be accessing its own globals table, which happens to be marik. You will likely find machines under marik.machines.
One way you could fix this is by using a different module pattern, such as this.
local M = {}
function M.pLoad()
-- ...
end
return M
local marik = require'marik'
-- ...
If you read around, you'll soon find out that there's at least a couple ways to make modules in Lua.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With