How to get a value returned from a seperate program?

Started by MonkeyButt, Jul 30, 2020, 06:35 AM

Previous topic - Next topic
I have a program that returns a table I need for other programs.
shell.run() returns a boolean so I can't use that

assert(loadfile(file)) compiles into a function so it's redundant.  The code is already in a function.  I get an error when I try anyways: attempt to index global myVariable (a function value)

assert(dofile(file)) errors: attempt to index global myVariable (a nil value)   probable because I have an error somewhere still testing

fixed up my code: I now get assertion failed error

Here is what my code looks like:
table = dofile(programThatReturnsTable)
print(table.x)

Lupus590

lua can return multiple values from it's functions, the table might be the second return value. Try checking the wiki

Quote from: Lupus590 on Jul 30, 2020, 07:43 AMlua can return multiple values from it's functions, the table might be the second return value. Try checking the wiki
dofile() returns whatever the file returns

function main()
    --I have a serialized table written to a txt file, somefile.txt
    fileToReadFrom = io.open("/somefile.txt")
    dataFromFile = filetoReadFrom:read("*a")
   
    --debug print, shows the serialized table
    print(dataFromFile)
    tableData = textutils.unserialize(dataFromFile)
   
    --debug print, shows the unserialized table, table: thm51b293awu
    print(tableData)
   
    --debug print, shows the value of mykey from table tableData, "dirt" for example
    print(tableData.mykey)
   
    --Pause so I can see print debug
    os.sleep(5)
   
    fileToReadFrom:close()
    return tableData
end

main()

tableINeedFromProgram = dofile("/file.lua")
myVariable = tableINeedFromProgram.mykey

First line from above errors: attempt to index global 'tableINeedFromProgram' (a nil value)

Lupus590

your file doesn't return anything. when lua runs a file you can imagine it as wrapping the file in a function call, but if your code doesn't return anything then this function that lua has made from your file is also not going to return anything.

you are going to want to change the last line to
return main()
because of this fake function thing, you don't actually need to define a main function as the body of the file serves that purpose.