Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Table Not Visible from API to Main Program

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
like image 784
Chris Grooms Avatar asked Jan 26 '26 02:01

Chris Grooms


1 Answers

I think I understand what's going on now. I assume you have two files, something like this.

marik.lua

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

main.lua

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.

marik.lua

local M = {}

function M.pLoad()
    -- ...
end

return M

main.lua

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.

like image 88
Ryan Stein Avatar answered Jan 27 '26 20:01

Ryan Stein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!