This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Bob's profile picture

Multiple return values into table

Started by Bob, 29 December 2014 - 01:22 PM
Bob #1
Posted 29 December 2014 - 02:22 PM
Hi,

I've been programming my own to-do list system in ComputerCraft (TPPI, survival), and I've stumbled upon something which I suspect is a bug/omission in the Lua implementation:

When I have a function that returns multiple arguments (for instance, term.current().getCursorPos()), and I want to directly use the results by putting them into a table like so:


ct = term.current()
local cy = {ct.getCursorPos()}[1]

I get the following error:


bios:366: [string "board"]:(line nr. of the "local cy..." line): unexpected symbol



While the Lua documentation states that this code should work, on this page, quoting:


function foo0 () end				  -- returns no results
function foo1 () return 'a' end	   -- returns 1 result
function foo2 () return 'a','b' end   -- returns 2 results

A constructor also collects all results from a call, without any adjustments:


a = {foo0()}		 -- a = {}  (an empty table)
a = {foo1()}		 -- a = {'a'}
a = {foo2()}		 -- a = {'a', 'b'}



Am I doing something wrong, perhaps misreading the documentation? Or is this a bug?
Dragon53535 #2
Posted 29 December 2014 - 03:12 PM

local cy = {ct.getCursorPos()}[1] --# This little [1] is invalid.
Can't do this…

local cy = {ct.getCursorPos()}
Works, however if you're wanting to only have the first index as a table to hold the data you need to do this:

local cy = {}
cy[1] = {ct.getCursorPos()}
Edited on 29 December 2014 - 02:12 PM
Lyqyd #3
Posted 29 December 2014 - 03:29 PM
The first index won't get you a "y" value of any sort anyway. If I recall correctly, this may work:


local cy = ({ct.getCursorPos()})[2]
Lignum #4
Posted 29 December 2014 - 03:29 PM

local cy = {ct.getCursorPos()}[1] --# This little [1] is invalid.
Can't do this…

local cy = {ct.getCursorPos()}
Works, however if you're wanting to only have the first index as a table to hold the data you need to do this:

local cy = {}
cy[1] = {ct.getCursorPos()}

You can also do this:

local cy = ({ ct.getCursorPos() })[1]

EDIT: Ninja'd
Edited on 29 December 2014 - 02:29 PM
MKlegoman357 #5
Posted 29 December 2014 - 04:46 PM
To explain why that didn't work: Lua just doesn't let you index a table directly after it's constructor ( { … } ) so you have to enclose it in parenthesis if you want to do that:


local t = {1, 2, 3}[2] --// wrong way

local t = ({1, 2, 3})[2] --// right way